【问题标题】:How to use multiprocessing to download images using requests?如何使用多处理通过请求下载图像?
【发布时间】:2020-06-22 14:46:18
【问题描述】:

我的代码很简单

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

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

如何使用多处理,更重要的是在使用这个sn-p时使用multiprocessing可以吗?

【问题讨论】:

  • 对于像下载这样具有高 IO 等待的代码,通常使用线程而不是进程就足够了。
  • 我同意@KlausD——事实上,使用多处理而不是线程实际上可能会使其变慢。

标签: python python-requests python-multiprocessing


【解决方案1】:

假设你有一个列表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)

与一个进程相比,多进程会提高速度。您可以对其进行测试,看看这些变化是否对您的情况很重要。

【讨论】:

    【解决方案2】:

    基本上这是一个 IO 绑定操作..所以我建议你使用 multithreading 而不是 multiprocessing..

    试试这个..

    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 的数量以加快处理速度。

    【讨论】:

      猜你喜欢
      • 2016-08-01
      • 2012-10-19
      • 1970-01-01
      • 1970-01-01
      • 2014-02-22
      • 1970-01-01
      • 2016-11-03
      • 1970-01-01
      • 2012-03-14
      相关资源
      最近更新 更多