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

Neh*_*rma 4 python

如果我在linux终端上运行python程序并按ctrl + c手动中止它,我怎样才能让我的程序在发生此事件时执行某些操作.

就像是:

if sys.exit():
    print "you chose to end the program"
Run Code Online (Sandbox Code Playgroud)

Ash*_*lla 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
Run Code Online (Sandbox Code Playgroud)

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

你选择结束该计划


Gam*_*iac 6

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

try:
    # some code here
except KeyboardInterrupt:
    print "You exited
Run Code Online (Sandbox Code Playgroud)

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

import time

try:
    while True:
        time.sleep(1)
        print "Hello"
except KeyboardInterrupt:
    print "No more Hellos"
Run Code Online (Sandbox Code Playgroud)