无论如何,当脚本运行时,如果Ctrl+c
被命中,我可以让我的脚本执行我的一个函数吗?
答案 0 :(得分:21)
看看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()
答案 1 :(得分:5)
不确定
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.
答案 2 :(得分:3)
使用KeyboardInterrupt exception并在except
区块中调用您的功能。