asyncio 在结果进来时收集产生的结果

Ale*_*ger 3 python python-asyncio

我希望能够从一组运行的任务中产生结果,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)
Run Code Online (Sandbox Code Playgroud)

目前,我可以使用该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])

Run Code Online (Sandbox Code Playgroud)

谢谢!

Mik*_*mov 7

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())
Run Code Online (Sandbox Code Playgroud)

结果:

Done 1
Done 2
Done 3
[Finished in 3 sec]
Run Code Online (Sandbox Code Playgroud)