Python中的新sys.path

1 投票
3 回答
944 浏览
提问于 2025-04-16 17:38

我在导入一个不在 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

有没有什么办法可以解决这个问题?

谢谢。

3 个回答

1

使用 from printline import printline 这行代码,然后就可以使用它了。

1
from test import println

println()
test.println()

或者你可以通过测试模块对象来调用 println 方法:

3
  1. 如果你使用 import test,那么你定义的函数会被导入到它自己的命名空间里,所以你必须用 test.printline() 来调用它。

  2. test 可能是你Python路径中另一个模块的名字,因为你添加的目录会被加到路径中,只有在其他地方找不到 test 的情况下,它才会被考虑。你可以试着把路径放到 sys.path 的最前面:

    sys.path.insert(0, "...")
    

在普通的Python环境中,问题很可能出在第一点,但如果你不想让你的脚本在将来出错,你也应该习惯第二点。

撰写回答