How do I capture SIGINT in Python?

前端 未结 12 1500
长发绾君心
长发绾君心 2020-11-21 22:54

I\'m working on a python script that starts several processes and database connections. Every now and then I want to kill the script with a Ctrl+C sign

12条回答
  •  天涯浪人
    2020-11-21 23:11

    And as a context manager:

    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
    

    To use:

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

    Nested handlers:

    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
    

    From here: https://gist.github.com/2907502

提交回复
热议问题