5

我有一个需要很长时间才能完成的程序。我希望它能够捕获SIGINT(ctrl-c) 并调用该self.save_work()方法。

就目前而言, mysignal_hander()不起作用,因为 self程序到达的时间没有定义signal_handler()

我该如何设置它以便self.save_work在 a 之后被调用SIGINT

#!/usr/bin/env python
import signal 

def signal_handler(signal, frame):    
    self.save_work()   # Does not work
    exit(1)
signal.signal(signal.SIGINT, signal_handler)

class Main(object):
    def do_stuff(self):
        ...
    def save_work(self):
        ...
    def __init__(self):
        self.do_stuff()
        self.save_work()

if __name__=='__main__':
    Main()
4

3 回答 3

4

如果你只想捕捉 ctr+c 那么你可以捕捉到KeyboardInterrupt异常:

class Main(object):
    def do_stuff(self):
        ...
    def save_work(self):
        ...
    def __init__(self):
        try:
            self.do_stuff()
        except KeyboardInterrupt:
            pass # Or print helpful info
        self.save_work()

并不是说我认为这毕竟是一个好的设计。看起来您需要使用函数而不是构造函数。

于 2009-11-04T15:05:12.373 回答
3

通常,“工作”涉及某种大循环。要驯服您的循环,并防止它在未知步骤中中断,您可以使用以下上下文管理器:

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

要使用:

import time

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

save_work()

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

于 2012-06-10T22:20:29.803 回答
2
import signal

def signal_handler(signal, frame):    
   #do some stuff

def main():
   #do some more stuff


if __name__=='__main__':
    signal.signal(signal.SIGINT, signal_handler)
    main()
于 2009-11-04T15:01:14.933 回答