[英]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.