注意:解决了.事实证明我正在导入同一模块的先前版本.
在StackOverflow上很容易找到类似的主题,其中有人遇到了NameError.但大多数问题涉及特定模块,解决方案通常是更新模块.
在我的情况下,我试图从我自己编写的模块中导入一个函数.该模块名为InfraPy,它肯定在sys.path上.InfraPy中的一个特定函数(称为listToText)返回一个NameError,但仅当我尝试将其导入另一个脚本时.在InfraPy中,if __name__=='__main__':listToText函数工作得很好.从InfraPy我可以毫无问题地导入其他功能.from InfraPy import *在我尝试使用listToText函数之前,包括在我的脚本中不会返回任何错误.
怎么会发生这种情况?
如何导入一个特定函数返回一个NameError,而导入同一个模块中的所有其他函数工作正常?
在MacOSX 10.6上使用python 2.6,在Windows 7上运行脚本也遇到了同样的错误,使用IronPython 2.6 for .NET 4.0
谢谢.
如果您认为有其他细节可以帮助解决这个问题,我很乐意提供它们.
根据要求,这里是InfraPy内部的功能定义:
def listToText(inputList, folder=None, outputName='list.txt'):
'''
Creates a text file from a list (with each list item on a separate line). May be placed in any given folder, but will otherwise be created in the working directory of the python interpreter.
'''
fname = outputName
if folder != None:
fname = folder+'/'+fname
f = open(fname, 'w')
for file in inputList:
f.write(file+'\n')
f.close()
Run Code Online (Sandbox Code Playgroud)
此功能在上方和外部定义 if __name__=='__main__':
我已经尝试过与脚本相关的InfraPy.最令人困惑的情况是,当InfraPy 与脚本位于同一个文件夹中,并且我使用导入时from InfraPy import listToText,我收到此错误:NameError: name listToText is not defined.同样,其他函数导入正常,它们都if __name__=='__main__':在InfraPy 之外定义.