我在从未存储在 sys.path 中的目录导入脚本时遇到困难。我在名为“Development”的目录中有一个保存为 test.py 的脚本,我正在尝试将开发目录添加到 sys.path,这样我就可以从我当前名为 index.py 的脚本中导入一个函数。
这是我的 index.py 代码:
import sys
sys.path.append ('/Users/master/Documents/Development/')
import test
printline()
printline() 在 test.py 中定义为:
def printline():
print "I am working"
这是我收到的错误:
Traceback (most recent call last):
File "/Users/master/Documents/index.py", line 6, in <module>
printline()
NameError: name 'printline' is not defined
关于如何让它发挥作用的任何想法?
谢谢。
最佳答案
如果你这样做
import test
,您定义的函数被导入到它自己的命名空间中,因此您必须将其引用为test.printline()
.test
可能是您的 Python 路径中另一个模块的名称,并且由于您插入的目录附加到路径,因此只有在test
时才会考虑它。无处可寻。尝试将路径插入到sys.path
的头部相反:sys.path.insert(0, "...")
在 vanilla Python 中,罪魁祸首可能是 #1,但如果您不希望您的脚本在未来崩溃,您也应该习惯 #2。
关于python - python 中的新 sys.path,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6004240/