我有一个名为 requests.py
的脚本,用于导入请求包 . 该脚本可以't access attributes from the package, or can'吨导入它们 . 为什么这不起作用,我该如何解决?
以下代码引发了 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'
The following code提出 ImportError
.
from requests.auth import AuthBase
class PizzaAuth(AuthBase):
"""Attaches HTTP Pizza Authentication to the given Request object."""
def __init__(self, username):
# setup any auth-related data here
self.username = username
def __call__(self, r):
# modify and return the request
r.headers['X-Pizza'] = self.username
return r
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
2 回答
发生这种情况是因为名为
requests.py
的本地模块会影响您尝试使用的已安装的requests
模块 . 当前目录前置于sys.path
,因此本地名称优先于已安装的名称 .出现这个问题时,额外的调试技巧是仔细查看Traceback,并意识到您所讨论的脚本名称与您尝试导入的模块匹配:
请注意您在脚本中使用的名称:
您要导入的模块:
requests
将模块重命名为其他名称以避免名称冲突 .
Python可能会在
requests.py
文件旁边生成requests.pyc
文件(在Python 3的__pycache__
目录中) . 在重命名后删除它,因为解释器仍将引用该文件,重新产生错误 . 但是,如果已删除py
文件,则__pycache__
中的pyc
文件不应影响您的代码 .在该示例中,将文件重命名为
my_requests.py
,删除requests.pyc
,然后再次成功运行打印<Response [200]>
.对于原始问题的编写者,以及那些搜索“AttributeError:module has no attribute”字符串的人,那么根据接受的答案的常见解释是,用户创建的脚本与库有名称冲突文件名 . 但请注意,问题可能不在于生成错误的脚本的名称(如上例所示),也不在于该脚本显式导入的库模块的任何名称中 . 可能需要一些 Sleuth 工作来确定导致问题的文件 .
作为说明问题的示例,假设您正在创建一个脚本,该脚本使用"decimal"库进行带十进制数的精确浮点计算,并将脚本命名为“
mydecimal.py
" that contains the line "import decimal
” . 这没有任何问题,但你发现它引发了这个错误:如果您之前编写了一个名为“
numbers.py
" because the " decimal " library calls on the standard library " numbers " but finds your old script instead. Even if you had deleted that, it might not end the problem because python might have converted that into bytecode and stored it in a cache as "numbers.pyc
”的脚本,那么就会发生这种情况,因此您也必须将其捕获 .