如何在Python中捕获SIGINT ?

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

在Perl中,我会这样做:

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


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

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

554619 次浏览

像这样用signal.signal注册你的处理程序:

#!/usr/bin/env python
import signal
import sys


def signal_handler(sig, frame):
print('You pressed Ctrl+C!')
sys.exit(0)


signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C')
signal.pause()

代码改编自在这里

更多关于signal的文档可以找到在这里。 < / p >

您可以通过捕获KeyboardInterrupt异常来处理CTRL+C。您可以在异常处理程序中实现任何清理代码。

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

import time, sys


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

您可以使用Python内置的信号模块中的函数来设置Python中的信号处理程序。具体来说,signal.signal(signalnum, handler)函数用于为signalnum信号注册handler函数。

来自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

作为一个上下文管理器:

import signal


class GracefulInterruptHandler(object):


def __init__(self, sig=signal.SIGINT):
self.sig = sig


def __enter__(self):


self.interrupted = False
self.released = False


self.original_handler = signal.getsignal(self.sig)


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


signal.signal(self.sig, handler)


return self


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


def release(self):


if self.released:
return False


signal.signal(self.sig, self.original_handler)


self.released = True


return True

使用方法:

with GracefulInterruptHandler() as h:
for i in xrange(1000):
print "..."
time.sleep(1)
if h.interrupted:
print "interrupted!"
time.sleep(2)
break

嵌套的处理程序:

with GracefulInterruptHandler() as h1:
while True:
print "(1)..."
time.sleep(1)
with GracefulInterruptHandler() as h2:
while True:
print "\t(2)..."
time.sleep(1)
if h2.interrupted:
print "\t(2) interrupted!"
time.sleep(2)
break
if h1.interrupted:
print "(1) interrupted!"
time.sleep(2)
break

从这里:https://gist.github.com/2907502

另一个片段

main作为主函数,将exit_gracefully作为CTRL + c处理程序

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

我调整了@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>)

马特·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

就我个人而言,我不能使用try/,除非KeyboardInterrupt,因为我使用的是阻塞的标准套接字(IPC)模式。因此,SIGINT是被提示的,但只有在接收到套接字上的数据后才会出现。

设置信号处理程序的行为与此相同。

另一方面,这只适用于实际的终端。其他启动环境可能不接受Ctrl+C,或者不预先处理信号。

此外,在Python中有“异常”和“BaseException”,它们的区别在于解释器需要自己干净地退出,因此一些异常的优先级高于其他异常(异常派生自BaseException)

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

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