【问题标题】:asyncio.gather not executing tasks when caller function requests input from STDIN?当调用者函数请求来自 STDIN 的输入时,asyncio.gather 不执行任务?
【发布时间】: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


    【解决方案1】:

    您需要等待 asyncio,并且您需要向它传递多个参数,而不是列表。

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

    【讨论】:

    • 这不是那里的主要问题:问题是“输入”在达到“收集”之前同步停止程序。
    • @jsbueno。当我运行它时工作正常。
    • 确实,OP 并没有抱怨我认为他是什么。
    • @jsbueno。是的,去过那里。
    猜你喜欢
    • 2021-10-23
    • 2016-09-04
    • 1970-01-01
    • 1970-01-01
    • 2021-05-29
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 2013-01-12
    相关资源
    最近更新 更多