python - AttributeError: 'module' object has no attribute

人盡茶涼 提交于 2019-12-24 00:37:22

问题


I'm trying this simple code:

import requests
print requests.__file__
r = requests.get('https://github.com/timeline.json')

It works flawlessly on the command line when I type the lines one by one, but not whenen when I execute it as a script or in Sublime Text 2. Here's the stack trace:

C:\Python27\lib\site-packages\requests\__init__.pyc
Traceback (most recent call last):
  File "C:\Users\Bruce\Desktop\http.py", line 1, in <module>
    import requests
  File "C:\Python27\lib\site-packages\requests\__init__.py", line 53, in <module>
    from requests.packages.urllib3.contrib import pyopenssl
  File "C:\Python27\lib\site-packages\requests\packages\__init__.py", line 3, in <module>
    from . import urllib3
  File "C:\Python27\lib\site-packages\requests\packages\urllib3\__init__.py", line 16, in <module>
    from .connectionpool import (
  File "C:\Python27\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 15, in <module>
    from http.client import HTTPConnection, HTTPException
  File "C:\Users\Bruce\Desktop\http.py", line 3, in <module>
    r = requests.get('https://github.com/timeline.json')
AttributeError: 'module' object has no attribute 'get'
[Finished in 0.2s with exit code 1]

Answers on 'Module object has no attribute 'get' Python error Requests? didn't help much.

Could this be some error in my ST2 Python build system? I tried removing all requests modules in case there were multiples of them by using pip and reinstalled them.


回答1:


Edit After reading the stacktrace again, you can see that urllib3 tries to import something from the http module. Your file is called http.py and is thus imported instead of the expected one.

The actual error happens because of the circular nature of the import. Since requests hasn't finished importing completely yet. The get function in requests isn't defined yet when the http import reaches import requests again.

Note: You will also want to always guard your entry point with the if __name__ == '__main__' construct. This will often avoid nasty errors for unsuspecting future developers (including yourself).



来源:https://stackoverflow.com/questions/17528149/python-attributeerror-module-object-has-no-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!