我对 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 中,我不再需要它们了。
再次感谢大家的帮助!