Python-如何在运行时检查程序是否被用户中止?

时间:2014-01-21 08:09:39

标签: python

如果我在linux终端上运行python程序并按ctrl + c手动中止它,那么当这个事件发生时,我怎么能让我的程序做点什么。

类似的东西:

if sys.exit():
    print "you chose to end the program"

3 个答案:

答案 0 :(得分:9)

您可以编写信号处理功能

import signal,sys
def signal_handling(signum,frame):
    print "you chose to end the program"
    sys.exit()

signal.signal(signal.SIGINT,signal_handling)
while True:
    pass

按Ctrl + c发送一个SIGINT中断,输出:

  

您选择结束该计划

答案 1 :(得分:6)

好吧,你可以使用KeyBoardInterrupt,使用try-except块:

try:
    # some code here
except KeyboardInterrupt:
    print "You exited

在命令行中尝试以下操作:

import time

try:
    while True:
        time.sleep(1)
        print "Hello"
except KeyboardInterrupt:
    print "No more Hellos"

答案 2 :(得分:1)

检查Python中的KeyboardInterrupt异常。

您可以将代码放在try块中,使用KeyboardInterrupt捕获except例外,并让用户知道他已退出。