Python 模块没有属性';func';

Python 模块没有属性';func';,python,import,spyder,func,Python,Import,Spyder,Func,我在导入模块时遇到问题,我使用Spyder 3.7作为编辑器,看起来没有导入: 第一个模块test.py: def func(): print('func() is tes.py') print("top level in test.py") if __name__=='__main__': print('test.py is being run directly') else: print('test.py is being imported into another

我在导入模块时遇到问题,我使用Spyder 3.7作为编辑器,看起来没有导入: 第一个模块test.py:

def func():
    print('func() is tes.py')
print("top level in test.py")
if __name__=='__main__':
    print('test.py is being run directly')
else:
    print('test.py is being imported into another module')
第二个是test2.py

import test

print ('top level in test2.py')
test.func()


if __name__=='__main__':
    print('test.py is being run directly')
else:
    print('test.py is being imported into another module')
两个文件都注册在同一文件夹中 当我执行test2.py时,我得到了这个错误

模块“test”没有属性“func”

我读了这本书,但对我没有帮助 有什么想法吗
谢谢。

从IDE运行时添加一个空的
\uuuu init\uuuu.py
。这将有助于ide将其识别为python包。若您通过终端运行它,它将在您运行
python test2.py
时执行

➜ cat test2.py 
import test

print ('top level in test2.py')
test.func()


if __name__=='__main__':
    print('test.py is being run directly')
else:
    print('test.py is being imported into another module')

# code execution
➜ python test2.py 
top level in test.py
test.py is being imported into another module
top level in test2.py
func() is tes.py
test.py is being run directly

您可能希望将模块命名为其他名称,因为它是一个标准的Python模块,显然您正在导入它,而不是您自己的
test.py
文件。

在Python中导入可能很难理解

一个简单的修复方法是通过以下方式将当前目录添加到
sys.path

导入操作系统,系统 path=os.path.abspath(_文件__) dirname=os.path.dirname(路径) 如果dirname不在sys.path中: sys.path.insert(0,目录名) python解释器将能够在同一文件夹中找到第二个文件

如果希望能够将整个目录作为模块导入,则可以 只需使用以下选项修改上一个选项:

dirname=os.path.dirname(os.path.dirname(path))

编辑:根据tdelaney的建议进行了更新

您可能希望将模块命名为其他名称,因为它是一个标准的Python模块。可能是您正在导入该文件,而不是您自己的
test.py
文件。是的@khelwood,这就是原因。我将两个文件的名称都改为1和2,它正常执行。谢谢,太好了。我将把它作为一个答案发布。我运行了你的代码(
pythonttest2.py
),它运行正常。没有错误。无法复制。是的。谢谢,避免使用标准库中的模块名称是一个非常好的主意(或者流行的库,例如numpy.py,这将是一个不好的名称)。但是python将脚本的目录放在python路径的前面,用户的
test.py
将屏蔽标准的
test.py
。我看不出这是如何解决问题的。可能有不同的导入程序可以解释这一点,但是我的linux机器上的标准python实现加载了本地
test.py
。可能有一些IDE对此有所帮助,但在大多数情况下并非如此。Python将脚本的目录添加到模块路径,以便识别该路径中的任何Python文件或包子目录。但是目录本身不是一个包,并且该目录中的
\uuuu init\uuuuuu.py
未加载。在执行此技巧之前,请尝试打印
sys.path
。在我的标准linux-python上,脚本的路径已经被python本身预先添加到路径中。这只是第二次添加。