繁体   English   中英

在.py文件中使用.py文件

[英]Using a .py file inside a .py file

我对python相当陌生,我一直只使用Jupyter Notebooks。 当我需要运行.py文件时,我通常将其保存在计算机中的某个位置,只需使用魔术命令%run

%run '/home/cody/.../Chapter 3/efld.py'
%run '/home/cody/.../Chapter 5/tan_vec.py'

然后,在下一个单元格中,我可以毫无问题地运行efld.py。 但是tan_vec.py使用efld.py,看起来像这样,

def tan_vec(r):
    import numpy as np
    #Finds the tangent vector to the electric field at point 'r'
    e = efld(r)
    e = np.array(e) #Turn 'e' into a numpy array so I can do math with it a little easier.
    emag = np.sqrt(sum(e**2)) #Magnitude of the 
    return e / emag

当我尝试运行时,出现错误;

"NameError: name 'efld' is not defined."

我在这里尝试了大多数事情但是没有一个可以工作。

我要在笔记本中运行py文件错误吗? 有没有更好的方式在笔记本中运行/调用py文件? 如何做到这一点,以便我可以在另一个py文件中运行一个py文件?

编辑

谢谢你们每一个人的帮助! 我只是想添加最终的代码,以防万一以后有人遇到这个问题并想看看我做了什么。

def tan_vec(r):
    #import sys
    #sys.path.insert(0, '/home/cody/Physics 331/Textbook Programs/Chapter 3')
    from efld import efld 
    import numpy as np
    #Finds the tangent vector to the electric field at point 'r'
    e = efld(r)
    e = np.array(e) #Turn 'e' into a numpy array so I can do math with it a little easier.
    emag = np.sqrt(sum(e**2)) #Magnitude of the 
    return e / emag

前两行被注释掉,因为仅当efld.py和tan_vec.py保存在不同的文件夹中时才需要使用它们。 我只是将efld的副本添加到同一文件夹和tan_vec中,而我不再需要它们了。

再次感谢您提供的所有帮助!

将文件放在jupyter根目录中。 然后只需在第一个单元格的顶部导入这些文件(现在称为模块)即可:

from efld import *
from tan_vec import *

如果一个要求另一个,则将导入放在相应文件的顶部,而不要插入jupyter。

鉴于这些模块自身不会引发任何异常,因此您可以在所有其他单元格中调用其中的所有函数。

e = efld(r)

请注意,两个文件中的所有功能均以不同的方式命名。


编辑 :如下面的注释中指出,您还可以直接导入函数:

from efld import efld as <whatever>

这样,您可以将函数重命名为<whatever>而不必重命名位于不同模块/文件中的具有相同名称的函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM