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

在Perl中,我会这样做:

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

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

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


当前回答

如果你想确保你的清理过程完成,我将通过使用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()

其他回答

与Matt J的答案相反,我使用了一个简单的对象。这使我有可能将这个处理程序解析到需要安全停止的所有线程。

class SIGINT_handler():
    def __init__(self):
        self.SIGINT = False

    def signal_handler(self, signal, frame):
        print('You pressed Ctrl+C!')
        self.SIGINT = True


handler = SIGINT_handler()
signal.signal(signal.SIGINT, handler.signal_handler)

在其他地方

while True:
    # task
    if handler.SIGINT:
        break

感谢已有的答案,但添加了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

来自Python的文档:

import signal
import time

def handler(signum, frame):
    print 'Here you go'

signal.signal(signal.SIGINT, handler)

time.sleep(10) # Press Ctrl+c here

另一个片段

将main作为main函数,将exit_elegant作为Ctrl+C处理程序

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        pass
    finally:
        exit_gracefully()

如果你想确保你的清理过程完成,我将通过使用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()