从脚本导入已安装包引发“AttributeError: 模块没有属性”或“ImportError: 无法导入名称”

2024-06-09 23:25:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为requests.py的脚本,用于导入请求包。脚本无法从包中访问属性,或者无法导入它们。为什么这不起作用,我该怎么解决?

下面的代码引发一个AttributeError

import requests

res = requests.get('http://www.google.ca')
print(res)
Traceback (most recent call last):
  File "/Users/me/dev/rough/requests.py", line 1, in <module>
    import requests
  File "/Users/me/dev/rough/requests.py", line 3, in <module>
    requests.get('http://www.google.ca')
AttributeError: module 'requests' has no attribute 'get'

下面的代码引发一个ImportError

from requests import get

res = get('http://www.google.ca')
print(res)
Traceback (most recent call last):
  File "requests.py", line 1, in <module>
    from requests import get
  File "/Users/me/dev/rough/requests.py", line 1, in <module>
    from requests import get
ImportError: cannot import name 'get'

或者从requests包中的模块导入的代码:

from requests.auth import AuthBase
Traceback (most recent call last):
  File "requests.py", line 1, in <module>
    from requests.auth import AuthBase
  File "/Users/me/dev/rough/requests.py", line 1, in <module>
    from requests.auth import AuthBase
ImportError: No module named 'requests.auth'; 'requests' is not a package

Tags: infrompydevimportauthgetline
2条回答

对于原始问题的编写者,以及那些搜索“attributeRor:module has no attribute”字符串的人,根据接受的答案,通常的解释是,用户创建的脚本与库文件名存在名称冲突。但是,请注意,问题可能不在生成错误的脚本的名称中(与上面的情况一样),也不在该脚本显式导入的库模块的任何名称中。要找出是哪个文件导致了这个问题,可能需要一点调查工作。

举个例子来说明这个问题,假设您正在创建一个脚本,它使用“decimal”库对十进制数进行精确的浮点计算,并将脚本命名为“mydecimal.py”,其中包含“import decimal”行。所有这些都没有问题,但您会发现它会引发以下错误:

AttributeError: 'module' object has no attribute 'Number'

如果您以前编写过一个名为“numbers.py”的脚本,那么就会发生这种情况,因为“decimal”库调用标准库“numbers”,但却找到了您的旧脚本。即使您删除了它,它也可能不会结束问题,因为python可能已经将其转换为字节码并将其作为“numbers.pyc”存储在缓存中,所以您还必须搜索它。

发生这种情况是因为名为requests.py的本地模块隐藏了您试图使用的已安装requests模块。当前目录位于sys.path前面,因此本地名称优先于已安装的名称。

出现这种情况时,另一个调试技巧是仔细查看回溯,并意识到所讨论脚本的名称与您尝试导入的模块匹配:

请注意脚本中使用的名称:

File "/Users/me/dev/rough/requests.py", line 1, in <module>

您试图导入的模块:requests

将模块重命名为其他名称以避免名称冲突。

Python可能会在requests.py文件旁边(在Python 3的__pycache__目录中)生成一个requests.pyc文件。在重命名之后也删除它,因为解释器仍会引用该文件,从而重新生成错误。但是,如果删除了py文件,__pycache__中的pyc文件应该不会影响代码。

在本例中,将文件重命名为my_requests.py,删除requests.pyc,然后再次运行将成功打印<Response [200]>

相关问题 更多 >