从脚本导入已安装的包会引发"AttributeError:module has no attribute"或"ImportError:无法导入名称"

idj*_*jaw 43 python exception python-module shadowing

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

以下代码提出了一个问题AttributeError.

import requests

res = requests.get('http://www.google.ca')
print(res)
Run Code Online (Sandbox Code Playgroud)
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'
Run Code Online (Sandbox Code Playgroud)

以下代码提出了一个问题ImportError.

from requests import get

res = get('http://www.google.ca')
print(res)
Run Code Online (Sandbox Code Playgroud)
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'
Run Code Online (Sandbox Code Playgroud)

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

from requests.auth import AuthBase
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)

idj*_*jaw 55

发生这种情况是因为您命名的本地模块会影响您尝试使用requests.py的已安装requests模块.当前目录是前置的sys.path,因此本地名称优先于已安装的名称.

出现这个问题时,额外的调试技巧是仔细查看Traceback,并意识到您所讨论的脚本名称与您尝试导入的模块匹配:

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

File "/Users/me/dev/rough/requests.py", line 1, in <module>
Run Code Online (Sandbox Code Playgroud)

您要导入的模块: requests

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

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

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


Dav*_*ove 13

对于原始问题的作者,以及那些搜索"AttributeError:module has no attribute"字符串的人,那么根据接受的答案的常见解释是,用户创建的脚本与库有名称冲突文件名.但请注意,问题可能不在于生成错误的脚本的名称(如上例所示),也不在于该脚本显式导入的库模块的任何名称中.可能需要一些侦探工作来确定导致问题的文件.

作为说明问题的示例,假设您正在创建一个脚本,该脚本使用"十进制"库进行带十进制数的精确浮点计算,并将脚本命名为" mydecimal.py",其中包含" import decimal" 行.没有任何问题,但你发现它引发了这个错误:

AttributeError: 'module' object has no attribute 'Number'
Run Code Online (Sandbox Code Playgroud)

如果您之前编写了一个名为" numbers.py" 的脚本,则会发生这种情况,因为"十进制"库调用标准库"数字",但会找到您的旧脚本.即使你删除了它,也可能不会结束问题,因为python可能已经将其转换为字节码并将其作为" numbers.pyc" 存储在缓存中,所以你也必须将其删除.


归档时间:

查看次数:

13492 次

最近记录:

5 年,11 月 前