我有一个名为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
发生这种情况是因为名为requests.py
的本地模块遮盖了您要使用的已安装requests
模块。当前目录位于sys.path
之前,因此本地名称优先于已安装的名称。
出现此问题时,一个额外的调试技巧是仔细查看Traceback,并意识到所涉及脚本的名称与您要导入的模块匹配:
注意您在脚本中使用的名称:
File "/Users/me/dev/rough/requests.py", line 1, in <module>
您要导入的模块:requests
将模块重命名为其他名称以避免名称冲突。
Python可能会在您的requests.pyc
文件旁边(在Python 3的requests.py
目录中)生成一个__pycache__
文件。重命名后也要删除该文件,因为解释器仍将引用该文件,从而重新产生错误。但是,如果删除了pyc
文件,则__pycache__
应该中的py
文件不会影响您的代码。
在此示例中,将文件重命名为my_requests.py
,删除requests.pyc
,然后再次运行将成功打印<Response [200]>
。
对于原始问题的作者,以及对于那些在“ AttributeError:模块没有属性”字符串上进行搜索的人,那么根据公认的答案,常见的解释是,用户创建的脚本的名称与库文件名。但是请注意,问题可能不在于生成错误的脚本名称(与上述情况相同),也不在于该脚本显式导入的库模块的名称。要弄清楚是哪个文件引起了问题,可能需要一些侦探工作。
作为说明问题的示例,假设您正在创建一个脚本,该脚本使用“十进制”库以十进制数字进行精确的浮点计算,并且将脚本“ mydecimal.py
”命名为包含行“ [ C0]”。这没有问题,但是您发现它会引发此错误:
import decimal
如果您已经先前编写了一个名为“ AttributeError: 'module' object has no attribute 'Number'
”的脚本,则会发生这种情况,因为“十进制”库调用标准库“ numbers”,但是会找到您的旧脚本。即使您删除了它,也可能不会解决问题,因为python可能已将其转换为字节码并将其存储为“ numbers.py
”在缓存中,因此您也必须对此进行深入研究。