【问题标题】:module has no attribute 'func'模块没有属性'func'
【发布时间】:2020-10-03 10:12:57
【问题描述】:

我在导入模块时遇到问题,我使用 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 1issue 2 但对我没有帮助 请有任何想法 谢谢。

【问题讨论】:

  • 你可能想给你的模块命名,因为test是一个标准的Python模块。可能是您正在导入该文件,而不是您自己的 test.py 文件。
  • 是的@khelwood,这就是原因。我将两个文件的名称都更改为一个和两个它可以正常执行。谢谢
  • 太棒了。我会发布它作为答案。
  • 我运行了你的代码 (python test2.py) 并且它有效。没有错误。无法重现。

标签: python import spyder func


【解决方案1】:

从 IDE 运行时添加一个空的 __init__.py。这将有助于将其识别为 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

【讨论】:

  • 也许有一些 IDE 可以提供帮助,但在大多数情况下并非如此。 Python 将脚本的目录添加到模块路径中,以便识别该路径中的任何 python 文件或包子目录。但是目录本身不是一个包,并且该目录中的__init__.py 没有加载。
【解决方案2】:

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

【讨论】:

  • 是的。谢谢
  • 避免来自标准库(或流行的库 - 例如 numpy.py 将是一个坏名字)的模块名称是一个非常好的主意。但是 python 将脚本的目录放在 python 路径的前面,用户的test.py 将掩盖标准的test.py。我不明白这是如何解决问题的。可能有不同的导入器可以解释这一点,但我的 linux 机器上的标准 python 实现会加载本地 test.py
【解决方案3】:

在 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 的建议

【讨论】:

  • 在这个技巧之前尝试打印sys.path。在我的标准 linux python 上,脚本的路径已经被 python 本身预先添加到路径中。这只是第二次添加它。
猜你喜欢
  • 1970-01-01
  • 2018-07-16
  • 1970-01-01
  • 2020-06-04
  • 2021-12-24
  • 2015-05-08
  • 2020-10-17
  • 2018-08-11
  • 2020-01-01
相关资源
最近更新 更多