我有一个名为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
对于原始问题的编写者,以及那些搜索“attributeRor:module has no attribute”字符串的人,根据接受的答案,通常的解释是,用户创建的脚本与库文件名存在名称冲突。但是,请注意,问题可能不在生成错误的脚本的名称中(与上面的情况一样),也不在该脚本显式导入的库模块的任何名称中。要找出是哪个文件导致了这个问题,可能需要一点调查工作。
举个例子来说明这个问题,假设您正在创建一个脚本,它使用“decimal”库对十进制数进行精确的浮点计算,并将脚本命名为“
mydecimal.py
”,其中包含“import decimal
”行。所有这些都没有问题,但您会发现它会引发以下错误:如果您以前编写过一个名为“
numbers.py
”的脚本,那么就会发生这种情况,因为“decimal”库调用标准库“numbers”,但却找到了您的旧脚本。即使您删除了它,它也可能不会结束问题,因为python可能已经将其转换为字节码并将其作为“numbers.pyc
”存储在缓存中,所以您还必须搜索它。发生这种情况是因为名为
requests.py
的本地模块隐藏了您试图使用的已安装requests
模块。当前目录位于sys.path
前面,因此本地名称优先于已安装的名称。出现这种情况时,另一个调试技巧是仔细查看回溯,并意识到所讨论脚本的名称与您尝试导入的模块匹配:
请注意脚本中使用的名称:
您试图导入的模块:
requests
将模块重命名为其他名称以避免名称冲突。
Python可能会在
requests.py
文件旁边(在Python 3的__pycache__
目录中)生成一个requests.pyc
文件。在重命名之后也删除它,因为解释器仍会引用该文件,从而重新生成错误。但是,如果删除了py
文件,__pycache__
中的pyc
文件应该不会影响代码。在本例中,将文件重命名为
my_requests.py
,删除requests.pyc
,然后再次运行将成功打印<Response [200]>
。相关问题 更多 >
编程相关推荐