【发布时间】:2022-01-16 21:06:28
【问题描述】:
在以下人为设计的示例中,我试图从 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())
但是在执行上述代码时,当输入相应的选项时,输出不包含所需的输出。
来自 STDIN 的输入 '1' 应该打印到 STDOUT:
task_1!
task_2!
来自 STDIN 的输入“2”应打印到 STDOUT:
task_2!
task_3!
当输入“1”或“二”时,没有输出。为什么tasks 没有被asyncio.gather 执行?
【问题讨论】:
标签: python input concurrency task python-asyncio