pyzmq Tornado ioloop:如何优雅地处理KeyboardInterrupt?

时间:2014-03-11 00:39:49

标签: python pyzmq keyboardinterrupt

我可以在我的pyzmq eventloop中找到KeyboardInterrupt:

try:
    ioloop.IOLoop.instance().start()
except KeyboardInterrupt:
    pass

但是这只会突然停止ioloop。我想检测KeyboardInterrupt并在清理后手动关闭ioloop。我怎么能这样做?

1 个答案:

答案 0 :(得分:5)

使用signal模块处理SIGINT

import signal
from tornado.ioloop import IOLoop

def on_shutdown():
    print('Shutting down')
    IOLoop.instance().stop()

if __name__ == '__main__':
    ioloop = IOLoop.instance()

    signal.signal(signal.SIGINT, lambda sig, frame: ioloop.add_callback_from_signal(on_shutdown))

    ioloop.start()