注:已解决。原来我正在导入同一模块的先前版本。
在 StackOverflow 上很容易找到类似的主题,其中有人遇到了 NameError。但是大多数问题都涉及特定的模块,解决方案通常是更新模块。
就我而言,我试图从我自己编写的模块中导入一个函数。该模块名为 InfraPy,它肯定在 sys.path 上。InfraPy 中的一个特定函数(称为 listToText)返回 NameError,但仅当我尝试将其导入另一个脚本时。在 InfraPy 下if __name__=='__main__':
,listToText 函数工作得很好。从 InfraPy 我可以毫无问题地导入其他功能。在我尝试使用 listToText 函数之前,包含from InfraPy import *
在我的脚本中不会返回任何错误。
这怎么会发生?
导入一个特定函数如何返回 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()
这个函数在上面和外面定义if __name__=='__main__':
我尝试根据脚本移动 InfraPy。最莫名其妙的情况是,当 InfraPy与脚本在同一个文件夹中,并且我使用 导入from InfraPy import listToText
时,我收到此错误:NameError: name listToText is not defined
. 同样,其他函数导入正常,它们都是if __name__=='__main__':
在 InfraPy 之外定义的。