python-AttributeError:“模块"对象没有属性 [英] python - AttributeError: 'module' object has no attribute

查看:359
本文介绍了python-AttributeError:“模块"对象没有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以下简单代码:

I'm trying this simple code:

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

当我一行一行地键入时,它在命令行上可以完美地工作,但是当我以脚本或Sublime Text 2的形式执行它时,它却不能正常工作.这是堆栈跟踪:

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]

>模块对象没有属性'get' Python错误请求?没有太大帮助.

这可能是我的ST2 Python构建系统中的某些错误吗?我尝试使用pip删除所有requests模块,以防它们有多个,然后重新安装它们.

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.

推荐答案

编辑再次阅读stacktrace后,您可以看到urllib3试图从http模块导入某些内容.您的文件称为http.py,因此将被导入,而不是预期的文件.

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.

由于导入的循环性质而发生实际错误.由于requests尚未完全完成导入.当http导入再次到达import requests时,尚未定义requests中的get函数.

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.

注意:您还将希望始终使用if __name__ == '__main__'构造来保护您的入口点.这通常可以避免令人讨厌的错误,因为这些错误会导致未来的开发人员(包括您自己)不知所措.

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).

这篇关于python-AttributeError:“模块"对象没有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆