[英]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.:在下面的人为示例中,我试图从 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())
However when executing the above code the output does not contain the desired output when the corresponding option is entered.但是,在执行上述代码时,当输入相应的选项时,output 不包含所需的 output。
Input '1' from STDIN should print to STDOUT:来自 STDIN 的输入“1”应打印到 STDOUT:
task_1!
task_2!
Input '2' from STDIN should print to STDOUT:来自 STDIN 的输入“2”应打印到 STDOUT:
task_2!
task_3!
When entering either '1' or 'two' there's no output.输入“1”或“2”时,没有 output。 Why aren't any of the
tasks
being executed by asyncio.gather
?为什么
asyncio.gather
没有执行任何tasks
?
You need to await the asyncio, and you need to pass it multiple arguments, not a list.您需要等待 asyncio,并且需要传递多个 arguments,而不是列表。
await asyncio.gather(*(t() for t in tasks))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.