【问题标题】:Asynchronously get and store images in python在python中异步获取和存储图像
【发布时间】:2013-08-22 10:08:12
【问题描述】:

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

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

我也看过 Grequests 库,但我无法从文档中了解是否可行或如何做到这一点。

【问题讨论】:

    标签: python urllib python-requests


    【解决方案1】:

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

    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)
    

    您可以选择创建一个线程池,从队列中获取urlsdests

    如果您使用的是 Python 3,它已经在 futures 模块中为您实现。

    【讨论】:

    • 好极了。到目前为止,我不知道我是如何在没有多线程的情况下生活的。谢谢
    • 非常简单实用的答案! map的使用非常棒(之前没用过,现在正在学习)
    • 请注意,这种使用 map 在 python 3 中不再起作用,因为不再直接评估 map(仅在需要实际数据时)。你可以使用[x.join() for x in threads]作为单行,或者写出两行for循环for x in threads: x.join()
    【解决方案2】:

    这样的东西应该可以帮助你

    import grequests
    urls = ['url1', 'url2', ....] # this should be the list of urls
    
        requests = (grequests.get(u) for u in urls)
        responses = grequests.map(requests)
        for response in responses:
            if 199 < response.status_code < 400:
                 name = generate_file_name()    # generate some name for your image file with extension like example.jpg
                 with open(name, 'wb') as f:    # or save to S3 or something like that
                      f.write(response.content)
    

    这里只有图像的下载是并行的,但将每个图像内容写入文件是顺序的,因此您可以创建一个线程或执行其他操作以使其并行或异步

    【讨论】:

      猜你喜欢
      • 2012-09-10
      • 1970-01-01
      • 2018-03-19
      • 2021-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多