当程序被 ctrl-c 中止时,实际引发了 KeyboardInterrupt 异常,导致程序退出。
方法一:
捕获 KeyboardInterrupt 并进行相应处理。
方法二:
使用 signal
#!/usr/bin/env python# -*- coding: utf-8 -*-import signalimport sysimport timedef signal_handler(signal, frame):# 这里可以做一些处理然后 sys.exit(0) 退出,或者什么都不做让程序无法被 ctrl-c 中止。print('强制退出。。。')sys.exit(0)def loop_func():signal.signal(signal.SIGINT, signal_handler) # 这里仅捕获 ctrl-c 信号for i in range(100):time.sleep(2)print(i)if __name__ == '__main__':loop_func()
signal 模块的其他用法参考 Python 官方文档中的 signal (暂未被翻译成中文)
https://docs.python.org/zh-cn/3/library/signal.html?highlight=signal#module-signal
