Skip to main content
 首页 » 编程设计

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

2025年05月04日10jillzhang

下面的代码是一个非异步代码的例子,请问有什么方法可以异步获取图片吗?

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 中为您实现了模块。