获取urllib2.urlopen的套接字HTTP的返回值

2024-05-06 23:09:57 发布

您现在位置:Python中文网/ 问答频道 /正文

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

>>> 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'
>>> 

Tags: inmostlibusrstdinlinesocketcall
1条回答
网友
1楼 · 发布于 2024-05-06 23:09:57

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

The problem is that urlib2 was changed to wrap an HTTPResponse object in a socket._fileobject to get a few more file methods. Except (as reported above) HTTPResponse doesn't have a fileno() method, so when _fileobject tries to use it, it blows up.

解决方案

向HTTPResponse添加适当的方法:

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

或者,也可以使用urllib.urlopen,而不是urrlib2.urlopen。在

这个问题有一个bug report;它在Python3和Python2.7中得到了修复。在

相关问题 更多 >