【问题标题】:Get socket for urllib2.urlopen return value for HTTP获取 urllib2.urlopen 的套接字 HTTP 的返回值
【发布时间】:2011-08-09 01:05:28
【问题描述】:

我正在尝试使用 urllib2 异步下载文件,但没有成功找到套接字(或其文件号)以等待 HTTP 请求的新数据。这是我已经尝试过的。

>>> from urllib2 import urlopen
>>> from select import select
>>> r = urlopen('http://stackoverflow.com/')
>>> select([r], [], [])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/socket.py", line 307, in fileno
    return self._sock.fileno()
AttributeError: HTTPResponse instance has no attribute 'fileno'
>>> r.fileno()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/socket.py", line 307, in fileno
    return self._sock.fileno()
AttributeError: HTTPResponse instance has no attribute 'fileno'
>>> r.fp.fileno()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/socket.py", line 307, in fileno
    return self._sock.fileno()
AttributeError: HTTPResponse instance has no attribute 'fileno'
>>> select([r.fp], [], [])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/socket.py", line 307, in fileno
    return self._sock.fileno()
AttributeError: HTTPResponse instance has no attribute 'fileno'
>>> 

【问题讨论】:

    标签: python urllib2 urllib


    【解决方案1】:

    http://www.velocityreviews.com/forums/t512553-re-urllib2-urlopen-broken.html

    问题是 urllib2 被更改为包装一个 HTTPResponse 对象 在 socket._fileobject 中获取更多文件方法。除了(如 上面报道)HTTPResponse 没有 fileno() 方法,所以当 _fileobject 尝试使用它,它会爆炸。

    解决办法

    向 HTTPResponse 添加适当的方法:

    def fileno(self):
        return self.fp.fileno()
    

    或者,或者,使用urllib.urlopen 而不是urrlib2.urlopen

    这个问题有一个bug report;它已在 Python 3 和 Python 2.7 中修复。

    【讨论】:

    猜你喜欢
    • 2015-02-05
    • 2010-10-25
    • 1970-01-01
    • 2013-01-25
    • 2016-04-22
    • 1970-01-01
    • 2011-09-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多