使用wxpython进行异步下载
好的,我有一个功能是打开一个网址,读取它的内容,然后把这些内容写入一个文件。问题是,当我这么做的时候,我的界面就会卡住。我知道我需要使用异步下载,但我似乎不太明白具体该怎么做!我打开的网址大约是10-20MB。
另外,http://docs.python.org/library/threading.html 这个链接对我有帮助吗?
我的代码是:
f = open("hello.txt",'wb')
datatowrite = urllib.urlopen(link).read()
f.write(datatowrite)
f.close()
如果能给个例子就太好了。
谢谢!
4 个回答
0
你需要把之前给的线程示例拿过来,结合到一个wxPython程序里。你可以参考这个网站上的示例,基本上只需要稍微修改一下,就能用上新的线程示例:http://www.blog.pythonlibrary.org/2010/05/22/wxpython-and-threads/
0
这里有个例子。在调用 asyncDownload
时,里面的 10
是超时时间,以秒为单位。你可能想把这个时间增加,或者干脆去掉它。下载的结果会保存在 thread.dataToWrite
下面。
import threading
import urllib2 as ul
class asyncDownload(threading.Thread):
def __init__(self,url,http_timeout):
threading.Thread.__init__(self)
self.url = url
self.http_timeout = http_timeout
def run(self):
self.dataToWrite = ul.urlopen(self.url,timeout=self.http_timeout).read()
url = 'http://www.yahoo.com'
thread = asyncDownload(url,10)
thread.run()
print('this thread is still running')
0
你可以使用asynhttp这个客户端来实现这个功能,因为你可能不想去看关于线程的文档。