python中的新sys.path

python中的新sys.path,python,import,sys.path,Python,Import,Sys.path,从未存储在sys.path中的目录导入脚本时遇到困难。我在一个名为“Development”的目录中保存了一个名为test.py的脚本,我正在尝试将开发目录添加到sys.path,以便从当前名为index.py的脚本导入一个函数 这是我的index.py代码: import sys sys.path.append ('/Users/master/Documents/Development/') import test printline() def printline(): prin

从未存储在sys.path中的目录导入脚本时遇到困难。我在一个名为“Development”的目录中保存了一个名为test.py的脚本,我正在尝试将开发目录添加到sys.path,以便从当前名为index.py的脚本导入一个函数

这是我的index.py代码:

import sys
sys.path.append ('/Users/master/Documents/Development/')
import test

printline()
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
printline()在test.py中定义为:

import sys
sys.path.append ('/Users/master/Documents/Development/')
import test

printline()
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 sys
sys.path.append ('/Users/master/Documents/Development/')
import test

printline()
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
回溯(最近一次呼叫最后一次):
文件“/Users/master/Documents/index.py”,第6行,在
printline()
NameError:未定义名称“printline”
有什么办法可以让它工作吗

谢谢

from test import println

println()
也可以通过测试模块对象调用println:

test.println()
也可以通过测试模块对象调用println:

test.println()
  • 如果执行
    import test
    ,则定义的函数将导入到其自己的命名空间中,因此必须将其称为
    test.printline()

  • test
    可能是Python路径中另一个模块的名称,并且由于插入的目录被附加到路径中,因此只有在其他地方找不到
    test
    时才会考虑它。尝试将路径插入到
    sys.path
    的头部:

    sys.path.insert(0, "...")
    
  • 在普通Python中,罪魁祸首可能是#1,但如果您不希望脚本将来崩溃,您也应该习惯于#2

  • 如果执行
    import test
    ,则定义的函数将导入到其自己的命名空间中,因此必须将其称为
    test.printline()

  • test
    可能是Python路径中另一个模块的名称,并且由于插入的目录被附加到路径中,因此只有在其他地方找不到
    test
    时才会考虑它。尝试将路径插入到
    sys.path
    的头部:

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

  • 在普通Python中,罪魁祸首很可能是#1,但如果您不希望脚本将来崩溃,您也应该习惯于#2。

    从printline导入printline使用
    ,然后使用它。

    从printline导入printline使用
    ,然后使用它