繁体   English   中英

当调用者 function 请求来自 STDIN 的输入时,asyncio.gather 不执行任务?

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

在下面的人为示例中,我试图从 STDIN 获取输入,并根据来自 STDIN 的输入使用asyncio.gather同时执行协程任务列表:

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

但是,在执行上述代码时,当输入相应的选项时,output 不包含所需的 output。

来自 STDIN 的输入“1”应打印到 STDOUT:

task_1!
task_2!

来自 STDIN 的输入“2”应打印到 STDOUT:

task_2!
task_3!

输入“1”或“2”时,没有 output。 为什么asyncio.gather没有执行任何tasks

您需要等待 asyncio,并且需要传递多个 arguments,而不是列表。

await asyncio.gather(*(t() for t in tasks))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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