我想在我的脚本中进行正确的CTRL+C处理,我一直在阅读一些示例,但我无法实现确定性行为。例如,给定以下脚本:
1 import signal
2 import time
3
4 def sigint_handler(signum, frame):
5 raise Exception('captured ctrl+c')
6
7 signal.signal(signal.SIGINT, sigint_handler)
8
9 c = True
10 while c:
11 try:
12 pass
13 except KeyboardInterrupt as e:
14 print 'captured keyboardexception'
15 print str(e)
16 except Exception as e:
17 print 'captured exception'
18 print str(e)
19 c = False
我可以得到这两个不同的输出
$ python ctrlc.py
^Ccaptured exception
captured ctrl+c
$ python ctrlc.py
^CTraceback (most recent call last):
File "ctrlc.py", line 12, in <module>
pass
File "ctrlc.py", line 5, in sigint_handler
raise Exception('captured ctrl+c')
Exception: captured ctrl+c
我尝试了不同的配置,也有双重异常处理和没有信号处理,但你总是可以得到不同的行为点击CTRL+C