如何在Python中捕获SIGINT?

时间:2009-07-10 22:49:21

标签: python controls signals

我正在开发一个启动多个进程和数据库连接的python脚本。我不时地想用 Ctrl + C 信号杀死脚本,我想做一些清理工作。

在Perl中我会这样做:

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

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

我如何在Python中进行此类模拟?

11 个答案:

答案 0 :(得分:692)

使用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()

代码改编自here

signal可以找到{{1}}的更多文档。

答案 1 :(得分:153)

您可以将其视为异常(KeyboardInterrupt),就像其他任何一样。创建一个新文件并使用以下内容从shell运行它以查看我的意思:

import time, sys

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

答案 2 :(得分:60)

作为上下文管理员:

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

答案 3 :(得分:26)

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

答案 4 :(得分:20)

来自Python的documentation

import signal
import time

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

signal.signal(signal.SIGINT, handler)

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

答案 5 :(得分:7)

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

答案 6 :(得分:5)

如果您想确保清理过程完成,我将使用Matt J's answer添加到SIG_IGN,以便进一步忽略<Table size="small" stickyHeader> <TableHead className={classes.head}> <TableRow> <StyledTableCell>Header 1</StyledTableCell> <StyledTableCell>Header 2</StyledTableCell> <StyledTableCell>Header 3</StyledTableCell> </TableRow> </TableHead> <TableBody> {props.results.map(row => { return( <TableRow key={row.id} hover> <TableCell>{row.one}</TableCell> <TableCell>{row.two}</TableCell> <TableCell>{row.three}</TableCell> </TableRow> )})} </TableBody> </Table> ,这将防止您的清理中断。

SIGINT

答案 7 :(得分:4)

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

答案 8 :(得分:4)

Matt J他的回答相反,我使用了一个简单的对象。这使我有可能将此处理程序解析为需要停止securlery的所有线程。

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

答案 9 :(得分:0)

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

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

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

此外,Python中还有“异常”和“ BaseExceptions”,它们在解释器需要干净退出本身的意义上有所不同,因此某些异常的优先级高于其他异常(异常是从BaseException派生的)

答案 10 :(得分:0)

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