简体   繁体   中英

asyncio.gather not executing tasks when caller function requests input from STDIN?

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 ?

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM