2011-08-09 83 views
5

我試圖做使用的urllib2文件的異步下載,但沒有成功地找到了插座(或它的fileno),以等待新數據的HTTP請求。這是我已經嘗試過的。找插座urllib2.urlopen返回值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' 
>>> 

回答

2

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

的問題是,urlib2改爲包裹在socket._fileobject HttpResponse對象 得到一些更多的文件的方法。除(如 上面報告)類HTTPResponse不具有的fileno()方法,因此,當 _fileobject試圖使用它,它鼓起。

溶液

添加一個適當的方法來類HTTPResponse:

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

,或者可選地,使用urllib.urlopen代替urrlib2.urlopen。這個問題有bug report;它在Python 3和Python 2.7中得到修復。

+0

謝謝,先生! –

+0

應該提出一個錯誤,如果沒有的話。 –

+0

http://bugs.python.org/issue1327971。它實際上看起來是你爲此提供修復的人嗎? – agf

相關問題