模块没有属性 'func'

module has no attribute '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 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'

我阅读了 issue 1 and issue 2 但对我没有帮助 请任何想法 谢谢。

添加一个空 __init__.py 而 运行 从 IDE 宁。这将有助于 ide 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

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

在 python 中导入可能很难理解。

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

import os, sys
path = os.path.abspath(__file__)
dirname = os.path.dirname(path)
if dirname not in sys.path:
    sys.path.insert(0, dirname)

python 解释器将能够在同一文件夹中找到第二个文件。

如果你希望能够将整个目录作为一个模块导入,你可以 只需修改前一个:

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

编辑:根据 tdelaney 的建议更新