下面的代码是一个非异步代码的例子,请问有什么方法可以异步获取图片吗?
import urllib
for x in range(0,10):
urllib.urlretrieve("http://test.com/file %s.png" % (x), "temp/file %s.png" % (x))
我也看到了 Grequests库,但如果可能的话,或者如何从文档中做到这一点,我想不通。
最佳答案
您不需要任何第三方库。只需为每个请求创建一个线程,启动线程,然后等待所有线程在后台完成,或者在下载图像时继续您的应用程序。
import threading
results = []
def getter(url, dest):
results.append(urllib.urlretreave(url, dest))
threads = []
for x in range(0,10):
t = threading.Thread(target=getter, args=('http://test.com/file %s.png' % x,
'temp/file %s.png' % x))
t.start()
threads.append(t)
# wait for all threads to finish
# You can continue doing whatever you want and
# join the threads when you finally need the results.
# They will fatch your urls in the background without
# blocking your main application.
map(lambda t: t.join(), threads)
您可以选择创建一个线程池,从队列中获取 urls
和 dests
。
如果您使用的是 Python 3,它已经在 futures
中为您实现了模块。
关于python - 在python中异步获取和存储图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18377475/