【发布时间】:2022-02-16 15:48:50
【问题描述】:
以下代码需要按 3 次 CTRL-C 才能结束,我怎样才能让它只以一次结束? (所以它在 Docker 中运行良好)
import asyncio
import time
def sleep_blocking():
print("Sleep blocking")
time.sleep(1000)
async def main():
loop = asyncio.get_event_loop()
await loop.run_in_executor(None, sleep_blocking)
try:
asyncio.run(main())
except KeyboardInterrupt:
print("Nicely shutting down ...")
我已经阅读了许多与 asyncio 相关的问题和答案,但还没有弄清楚这一点。第一个 CTRL-C 什么都不做,第二个打印“很好地关闭...”然后挂起。第三个 CTRL-C 打印一个丑陋的错误。
我使用的是 Python 3.9.10 和 Linux。
(编辑:每条评论更新代码@mkrieger1)
【问题讨论】:
-
如果将
loop.run_until_complete(loop.run_in_executor(...))替换为await loop.run_in_executor(...)会发生什么? -
@mkrieger1 那么它需要 3 个 CTRL-C :) 真的。第一个似乎没有做任何事情,第二个打印
"Nicely shutting down ...",第三个又是丑陋的错误
标签: python python-asyncio