您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python请求:不要等待请求完成

Python请求:不要等待请求完成

我用multiprocessing.dummy.Pool。我在模块级别创建一个单例线程池,然后用于pool.apply_async(requests.get, [params])启动任务。

该命令给了我一个未来,我可以将它无限期地与其他未来添加到列表中,直到我想收集全部或部分结果为止。

multiprocessing.dummy.Pool 出于所有逻辑和理由,是一个THREAD池而不是一个进程池。

示例(只要安装了请求,就可以在Python 2和3中使用):

from multiprocessing.dummy import Pool

import requests

pool = Pool(10) # Creates a pool with ten threads; more threads = more concurrency.
                # "pool" is a module attribute; you can be sure there will only
                # be one of them in your application
                # as modules are cached after initialization.

if __name__ == '__main__':
    futures = []
    for x in range(10):
        futures.append(pool.apply_async(requests.get, ['http://example.com/']))
    # futures is Now a list of 10 futures.
    for future in futures:
        print(future.get()) # For each future, wait until the request is
                            # finished and then print the response object.

这些请求将同时执行,因此运行所有十个请求所花的时间不应超过最长的一个。该策略将仅使用一个cpu内核,但这不会成为问题,因为几乎所有时间都将花费在等待I / O上。

python 2022/1/1 18:25:25 有475人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶