In the following contrived example I am attempting to get input from STDIN and execute a list of coroutine tasks concurrently using asyncio.gather based on the input from STDIN.:
import asyncio
async def task_1():
print('task_1!')
async def task_2():
print('task_2!')
async def task_3():
print('task_3!')
async def task_4():
print('task_4!')
async def main():
opts = {
'1': [task_1, task_2],
'2': [task_3, task_4]
}
while True:
opt = input('Enter option: ')
tasks = opts.get(opt)
asyncio.gather(t() for t in tasks)
if __name__ == '__main__':
asyncio.run(main())
However when executing the above code the output does not contain the desired output when the corresponding option is entered.
Input ‘1’ from STDIN should print to STDOUT:
task_1! task_2!
Input ‘2’ from STDIN should print to STDOUT:
task_2! task_3!
When entering either ‘1’ or ‘two’ there’s no output. Why aren’t any of the tasks being executed by asyncio.gather?
Advertisement
Answer
You need to await the asyncio, and you need to pass it multiple arguments, not a list.
await asyncio.gather(*(t() for t in tasks))