如何覆盖键盘中断? (蟒蛇)

时间:2011-08-09 01:26:18

标签: python signals interrupt

无论如何,当脚本运行时,如果Ctrl+c被命中,我可以让我的脚本执行我的一个函数吗?

3 个答案:

答案 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区块中调用您的功能。