在 while 循环中使用 asyncio.sleep() 时 Control+C 不起作用

Control+C not working while using asyncio.sleep() in while loop

我似乎不明白为什么 CTL+C 不起作用。

我认为我还不了解异步函数的工作方式 asyncio.sleep()

然而,我发现 this bug report which might be related as well as people using event loops with async functions in python. Also, there are questions like 但他们并没有真正回答我的问题或提供见解。

async def set_maintain_countdown_message(countdown, message):
    try:
        countdown_message = await app.send_message(
            message.chat.id,
            await get_formated_countdown(countdown)
            )
        await asyncio.sleep(random.randint(4, 8))
        while countdown['state'] == 'active':
            await countdown_message.edit(
                await get_formated_countdown(countdown)
            )
            await asyncio.sleep(random.randint(4, 8))

    except FloodWait as e:
        await asyncio.sleep(e.x)

您可以使用 custom signal handlers 来实现它。

不幸的是,默认情况下 asyncio 不能那样工作,主要原因是:如果同时有多个协程在等待,它会取消哪个?

此外,我不会深入探讨 asyncio 是如何在内部实现的,我在 different question 上回答过这个问题,但解释器实际上并没有在那行代码处休眠,所以 KeyboardInterrupt不会被扔到那里。

创建自定义信号处理程序来处理 SIGINT 可能正是您要找的。

请记住 - 如果您不使用 asyncio.run() 到 运行 代码,您必须确保使用 loop.shutdown_asyncgens() 优雅地关闭协程(取消所有内容)。