问题描述
在 Windows 上使用 Python 3.4.1,我发现在执行 asyncio 事件时循环,我的程序不能被中断(即在终端中按Ctrl+C).更重要的是,SIGINT 信号被忽略.相反,我已经确定 SIGINT 在不在事件循环中时被处理.
Using Python 3.4.1 on Windows, I've found that while executing an asyncio event loop, my program can't be interrupted (i.e. by pressing Ctrl+C in the terminal). More to the point, the SIGINT signal is ignored. Conversely, I've determined that SIGINT is handled when not in an event loop.
为什么在执行 asyncio 事件循环时忽略了 SIGINT?
Why is it that SIGINT is ignored when executing an asyncio event loop?
下面的程序应该演示问题 - 在终端中运行它并尝试按 Ctrl+C 停止它,它应该继续运行:
The below program should demonstrate the problem - run it in the terminal and try to stop it by pressing Ctrl+C, it should keep running:
import asyncio
import signal
# Never gets called after entering event loop
def handler(*args):
print('Signaled')
signal.signal(signal.SIGINT, handler)
print('Event loop starting')
loop = asyncio.SelectorEventLoop()
asyncio.set_event_loop(loop)
loop.run_forever()
print('Event loop ended')
请参阅关于官方(郁金香)邮件的讨论列表.
See discussion on official (Tulip) mailing list.
推荐答案
我找到了一种解决方法,即安排定期回调.在此运行时,SIGINT 显然已被处理:
I've found a workaround, which is to schedule a periodic callback. While this running, SIGINT is apparently processed:
import asyncio
def wakeup():
# Call again
loop.call_later(0.1, wakeup)
print('Event loop starting')
loop = asyncio.SelectorEventLoop()
# Register periodic callback
loop.call_later(0.1, wakeup)
asyncio.set_event_loop(loop)
loop.run_forever()
print('Event loop ended')
不确定为什么这是必要的,但它表明在事件循环等待事件(轮询")时信号被阻塞.
Not sure why this is necessary, but it indicates that signals are blocked while the event loop waits for events ("polls").
此事已在官方讨论(Tulip) 邮件列表,我的解决方法显然是目前要走的路.
The matter has been discussed on the official (Tulip) mailing list, my workaround is apparently the way to go as of now.
据称已进入 Python 3.5,所以希望我的解决方法会被那个 Python 版本淘汰.
A fix has supposedly made its way into Python 3.5, so hopefully my workaround will be made obsolete by that Python version.
这篇关于为什么在 asyncio 事件循环运行时我无法捕获 SIGINT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!