我正在嘗試爲Linux構建一個下載加速器。我的程序使用了gevent,os和urllib2。我的程序收到一個URL並嘗試同時下載文件。我所有的代碼都是有效的。我唯一的問題是,urllib2.urlopen.read()阻止我同時運行.read()函數。Python,gevent,urllib2.urlopen.read(),下載加速器
這是拋出我的例外。
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/gevent/greenlet.py", line 405, in run
result = self._run(*self.args, **self.kwargs)
File "gevent_concurrent_downloader.py", line 94, in childTasklet
_tempRead = handle.read(divisor) # Read/Download part
File "/usr/lib/python2.7/socket.py", line 380, in read
data = self._sock.recv(left)
File "/usr/lib/python2.7/httplib.py", line 561, in read
s = self.fp.read(amt)
File "/usr/lib/python2.7/socket.py", line 380, in read
data = self._sock.recv(left)
File "/usr/lib/pymodules/python2.7/gevent/socket.py", line 407, in recv
wait_read(sock.fileno(), timeout=self.timeout, event=self._read_event)
File "/usr/lib/pymodules/python2.7/gevent/socket.py", line 153, in wait_read
assert event.arg is None, 'This event is already used by another greenlet: %r' % (event.arg,)
AssertionError: This event is already used by another greenlet: (<Greenlet at 0x2304958: childTasklet(<__main__.NewFile object at 0x22c4390>, 4595517, <addinfourl at 37154616 whose fp = <socket._fileob, 459551, 1)>, timeout('timed out',))
<Greenlet at 0x2304ea8: childTasklet(<__main__.NewFile object at 0x22c4390>,4595517, <addinfourl at 37154616 whose fp = <socket._fileob, 7, -1)failed with AssertionError
我的程序的工作原理是通過調用獲取URL中的文件字節大小:
urllib2.urlopen(URL).info().get("Content-Length")
和除數將文件大小,從而打破了下載過程分成幾部分。在這個例子中,我將下載分成10個部分。
每個greenlet在此fassion運行一個命令:
urllib2.urlopen(URL).read(offset)
這裏是我的代碼的鏈接託管在pastie:http://pastie.org/3253705
感謝您的幫助!
僅供參考:我在Ubuntu 11.10上運行。
irc.freenode.net上的#gevent頻道可能會提供一些幫助。 – Anorov