Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python asyncio在收到结果时收集结果_Python_Python Asyncio - Fatal编程技术网

Python asyncio在收到结果时收集结果

Python asyncio在收到结果时收集结果,python,python-asyncio,Python,Python Asyncio,我希望能够从gather运行的一组任务中产生结果,因为这些任务需要进一步处理 #不是真正的代码,而是一个示例 asyncio.gather中的async响应(*[aiohttp.get(url)用于['https://www.google.com', 'https://www.amazon.com']]): 等待过程_响应(响应) 目前,我可以使用gather方法同时运行所有get,但必须等到它们全部完成后才能处理它们。我对Python async/await还是个新手,所以可能有一些明显的方

我希望能够从
gather
运行的一组任务中产生结果,因为这些任务需要进一步处理

#不是真正的代码,而是一个示例
asyncio.gather中的async响应(*[aiohttp.get(url)用于['https://www.google.com', 'https://www.amazon.com']]):
等待过程_响应(响应)
目前,我可以使用
gather
方法同时运行所有
get
,但必须等到它们全部完成后才能处理它们。我对Python async/await还是个新手,所以可能有一些明显的方法我不知道

#我现在能做什么
responses=wait asyncio.gather(*[aiohttp.get(url)用于[]中的url)https://www.google.com', 'https://www.amazon.com']])
等待asyncio.gather(*[处理响应中的响应(响应)))

谢谢

收集
正如您已经指出的,将等待所有协同程序完成,因此您需要找到另一种方法

例如,您可以使用似乎完全符合您需要的函数

import asyncio


async def echo(t):
    await asyncio.sleep(t)
    return t



async def main():
    coros = [
        echo(3),
        echo(2),
        echo(1),
    ]

    for first_completed in asyncio.as_completed(coros):
        res = await first_completed
        print(f'Done {res}')


asyncio.run(main())
结果:

Done 1
Done 2
Done 3
[Finished in 3 sec]

是的,这似乎是我想要的,谢谢。我注意到,在许多情况下,
as_completed
gather
之间的差异可能非常小,有时
gather
占上风。这是一个意外的结果,值得注意。@AlejandroWainzinger“完成”和“收集”之间的差异可能非常小,只有在协同程序运行时间相似的情况下才应该如此。如果协同程序的运行时间有很大差异,
as_completed
应该比
gather
更快地生成更快的结果,后者总是在返回任何内容之前等待所有结果。