Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to await a list of tasks in python?

In .Net C#, there is a function Task.WhenAll that can take a list of tasks to await them. What should I use in python? I am trying to do the same with this:

tasks = ...  # list of coroutines
    
for task in tasks:
    await task
like image 607
Ernest Rutherford Avatar asked Sep 17 '25 17:09

Ernest Rutherford


2 Answers

After adding tasks to a list, you should use asyncio.gather that gives coroutines as an argument list and executes them asynchronously. Also, you could use asyncio.create_task that takes a coroutine and calls concurrent tasks in the event loop.

import asyncio


async def coro(i):
    await asyncio.sleep(i//2)


async def main():
    tasks = []
    for i in range(5):
        tasks.append(coro(i))
    await asyncio.gather(*tasks)


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    loop.close()
like image 90
Artyom Vancyan Avatar answered Sep 19 '25 06:09

Artyom Vancyan


Use asyncio.gather if you're on Python 3.7 or above. From the docs:

Run awaitable objects in the aws sequence concurrently. If any awaitable in aws is a coroutine, it is automatically scheduled as a Task. If all awaitables are completed successfully, the result is an aggregate list of returned values. The order of result values corresponds to the order of awaitables in aws.

like image 30
aIKid Avatar answered Sep 19 '25 06:09

aIKid