提问者:小点点

如何使用多处理来使用请求下载图像?


我截取的代码相当简单

def download(url):
    response = requests.get(url)
    with open(path, 'wb') as handle:
        handle.write(response.content)

但是我的代码下载了将近10,000张图像,这使得这个过程非常耗时。

如何利用多处理,更重要的是在使用此代码段时使用multiprocessing是否可以?


共2个答案

匿名用户

假设您有一个urls列表,您可以像这样使用多处理:

from multiprocessing import Pool

def download(url):
    response = requests.get(url)
    with open(path, 'wb') as handle:
        handle.write(response.content)

pool = Pool()
pool.map(download, urls)

与一个进程相比,多重处理将提高速度。 您可以测试它,看看在您的情况下更改是否显著。

匿名用户

基本上这是一个IO绑定操作。。所以我建议你使用多线程而不是多处理。。

试试这个。。

from concurrent.futures import ThreadPoolExecutor

def download(url):
    response = requests.get(url)
    with open(path, 'wb') as handle:
        handle.write(response.content)

with ThreadPoolExecutor(max_workers=8) as executor:
    executor.map(download, urls) #urls=[list of url]

您可以尝试更改max_workers的数量,以根据系统的处理能力加快处理速度。