我希望能够在 gather
运行的一组任务进入进一步处理时生成结果。
# Not real code, but an example
async for response in asyncio.gather(*[aiohttp.get(url) for url in ['https://www.google.com', 'https://www.amazon.com']]):
await process_response(response)
目前,我可以使用gather
方法同时运行所有get
,但必须等到它们全部完成才能处理它们。我对 Python async/await 还很陌生,所以也许我缺少一些明显的方法来做到这一点。
# What I can do now
responses = await asyncio.gather(*[aiohttp.get(url) for url in ['https://www.google.com', 'https://www.amazon.com']])
await asyncio.gather(*[process_response(response) for response in responses])
谢谢!
最佳答案
gather
正如您已经指出的,将等待所有协程完成,因此您需要找到另一种方法。
例如,您可以使用函数 asyncio.as_completed这似乎正是你想要的。
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]
关于python - asyncio 收集产生的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58210422/