【问题标题】:How to run a task in the background until user inputs?如何在后台运行任务直到用户输入?
【发布时间】:2020-12-31 11:15:30
【问题描述】:

我来自 .NET 背景,但我注意到 asyncio 的行为与 .NET 中的 asyncawait 不同:

我正在努力实现以下目标:

  1. 启动一项计算任务 (a)
  2. 启动一个等待用户输入退出的任务 (b)
  3. 等待任务b(用户已退出)
  4. 取消任务a

以下根本不执行任务a

processing = asyncio.create_task(do_processing())

user_finished = asyncio.create_task(stdin_listener())

await user_finished

processing.cancel()

我理解的原因是因为从未等待processing,但是如果我等待此任务,它将永远不会返回,因为它永远不会到达cancel()

我浏览了文档,但找不到这个简单的示例,或者无法将其拼凑在一起。只是对这个API不熟悉,请赐教。

编辑: 我发现上面的任务处理是正确的。但是,在方法@​​987654332@ 中,我调用了:

input("Press Q to quit\n")

这是阻塞的。我将研究此调用的其他方法。

【问题讨论】:

  • 没有看到 do_processingstdin_listener 很难提供有意义的帮助,但我的猜测是后者不会等待任何返回事件循环的东西,所以前者永远没有机会开始。
  • 好的,太好了。是的,这是有道理的。谢谢你的解释。

标签: python python-3.x python-asyncio


【解决方案1】:

我决定使用 SIGINT 来平仓:

exiting = False


        async def do_processing():
            global exiting
            while not exiting:
                await asyncio.sleep(1)
                # do processing here


        def handler(signal_received, frame):
            global exiting
            # Handle any cleanup here
            print('SIGINT or CTRL-C detected. Exiting gracefully')
            exiting = True

        signal(SIGINT, handler)

        await asyncio.create_task(do_processing())

        # post processing

进一步解释的链接: https://www.devdungeon.com/content/python-catch-sigint-ctrl-c

【讨论】:

  • 请阅读How to Answer。虽然此链接的内容实际上可能解决问题,但本网站不鼓励仅提供链接的答案。链接往往会中断,然后答案就失去了价值。最好将链接的基本部分作为文本包含在答案本身中,并提供链接作为参考。您的纯文本答案看起来像:I've decided to use SIGINT to close out, based on this pattern: <line>,它没有提供太多信息。如果您认为单独的链接可以提供帮助,请将其作为评论发布(如果您有 50 个代表)。
猜你喜欢
  • 2020-11-13
  • 2020-10-24
  • 1970-01-01
  • 1970-01-01
  • 2020-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多