【发布时间】:2011-08-09 01:26:17
【问题描述】:
当脚本运行时Ctrl+c 被点击时,我是否可以让我的脚本执行我的功能之一?
【问题讨论】:
-
查看stackoverflow.com/questions/4205317/… 了解多个选项。
当脚本运行时Ctrl+c 被点击时,我是否可以让我的脚本执行我的功能之一?
【问题讨论】:
当然。
try:
# Your normal block of code
except KeyboardInterrupt:
# Your code which is executed when CTRL+C is pressed.
finally:
# Your code which is always executed.
【讨论】:
看看signal handlers。 CTRL-C 对应于SIGINT(posix 系统上的信号#2)。
例子:
#!/usr/bin/env python
import signal
import sys
def signal_handler(signal, frame):
print 'You pressed Ctrl+C - or killed me with -2'
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
print 'Press Ctrl+C'
signal.pause()
【讨论】:
kill -2 [pid] 时,这个也应该触发信号处理程序
KeyboardInterrupt异常,后者不会。但我不确定为什么会这样的实施细节。
使用KeyboardInterrupt exception 并在except 块中调用您的函数。
【讨论】: