在python中异步获取和存储图像

Dio*_*lor 1 python urllib python-requests

以下代码是非异步代码的示例,有没有办法异步获取图像?

import urllib
for x in range(0,10):
        urllib.urlretrieve("http://test.com/file %s.png" % (x), "temp/file %s.png" % (x))
Run Code Online (Sandbox Code Playgroud)

我也看过Grequests库,但如果可能或者如何从文档中做到这一点我就无法理解.

Vik*_*kez 10

您不需要任何第三方库.只需为每个请求创建一个线程,启动线程,然后等待所有这些线程在后台完成,或者在下载图像时继续应用程序.

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)
Run Code Online (Sandbox Code Playgroud)

您也可以选择创建一个线程池,将获得urlsdests从队列中.

如果你正在使用Python 3,它已经在futures模块中为你实现了.