我正在编写一个python脚本,启动几个进程和数据库连接。有时我想用Ctrl+C信号终止脚本,我想做一些清理工作。

在Perl中,我会这样做:

$SIG{'INT'} = 'exit_gracefully';

sub exit_gracefully {
    print "Caught ^C \n";
    exit (0);
}

如何在Python中进行类似操作?


当前回答

您可以使用Python内置信号模块中的函数来设置Python中的信号处理程序。特别是信号。Signal (signalnum, handler)函数用于为信号signalnum注册处理函数。

其他回答

如果你想确保你的清理过程完成,我将通过使用SIG_IGN添加到Matt J的答案,这样进一步的SIGINT将被忽略,这将防止你的清理被打断。

import signal
import sys

def signal_handler(signum, frame):
    signal.signal(signum, signal.SIG_IGN) # ignore additional signals
    cleanup() # give your process a chance to clean up
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler) # register the signal with the signal handler first
do_stuff()

您可以使用Python内置信号模块中的函数来设置Python中的信号处理程序。特别是信号。Signal (signalnum, handler)函数用于为信号signalnum注册处理函数。

感谢已有的答案,但添加了signal.getsignal()

import signal

# store default handler of signal.SIGINT
default_handler = signal.getsignal(signal.SIGINT)
catch_count = 0

def handler(signum, frame):
    global default_handler, catch_count
    catch_count += 1
    print ('wait:', catch_count)
    if catch_count > 3:
        # recover handler for signal.SIGINT
        signal.signal(signal.SIGINT, default_handler)
        print('expecting KeyboardInterrupt')

signal.signal(signal.SIGINT, handler)
print('Press Ctrl+c here')

while True:
    pass

你可以像对待其他异常一样对待它(KeyboardInterrupt)。创建一个新文件,并在shell中运行它,包含以下内容,看看我的意思:

import time, sys

x = 1
while True:
    try:
        print x
        time.sleep(.3)
        x += 1
    except KeyboardInterrupt:
        print "Bye"
        sys.exit()

我调整了@udi的代码来支持多个信号(没什么特别的):

class GracefulInterruptHandler(object):
    def __init__(self, signals=(signal.SIGINT, signal.SIGTERM)):
        self.signals = signals
        self.original_handlers = {}

    def __enter__(self):
        self.interrupted = False
        self.released = False

        for sig in self.signals:
            self.original_handlers[sig] = signal.getsignal(sig)
            signal.signal(sig, self.handler)

        return self

    def handler(self, signum, frame):
        self.release()
        self.interrupted = True

    def __exit__(self, type, value, tb):
        self.release()

    def release(self):
        if self.released:
            return False

        for sig in self.signals:
            signal.signal(sig, self.original_handlers[sig])

        self.released = True
        return True

这段代码支持键盘中断调用(SIGINT)和SIGTERM (kill <process>)