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.:
JavaScript
x
27
27
1
import asyncio
2
3
async def task_1():
4
print('task_1!')
5
6
async def task_2():
7
print('task_2!')
8
9
async def task_3():
10
print('task_3!')
11
12
async def task_4():
13
print('task_4!')
14
15
async def main():
16
opts = {
17
'1': [task_1, task_2],
18
'2': [task_3, task_4]
19
}
20
while True:
21
opt = input('Enter option: ')
22
tasks = opts.get(opt)
23
asyncio.gather(t() for t in tasks)
24
25
if __name__ == '__main__':
26
asyncio.run(main())
27
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:
JavaScript
1
3
1
task_1!
2
task_2!
3
Input ‘2’ from STDIN should print to STDOUT:
JavaScript
1
3
1
task_2!
2
task_3!
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.
JavaScript
1
2
1
await asyncio.gather(*(t() for t in tasks))
2