我可以在pyzmq eventloop中捕获KeyboardInterrupt:

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


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

最佳答案

使用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()

10-08 00:51