Python - Trap all signals

前端 未结 8 1448
慢半拍i
慢半拍i 2020-11-30 04:54

In python 2.6 under Linux, I can use the following to handle a TERM signal:

import signal
def handleSigTERM():
    shutdown()
signal.signal(signal.SIGTERM, h         


        
8条回答
  •  执笔经年
    2020-11-30 05:30

    Here's a 2/3 compatible way which doesn't have as many pitfalls as the others:

    from itertools import count
    import signal
    
    def set_all_signal_signals(handler):
        """Set all signals to a particular handler."""
        for signalnum in count(1):
            try:
                signal.signal(signalnum, handler)
                print("set {}".format(signalnum))
            except (OSError, RuntimeError):
                # Invalid argument such as signals that can't be blocked
                pass
            except ValueError:
                # Signal out of range
                break
    

    Since signalnum is just a number, iterate over 1 to out of range setting the signal to a particular handle.

提交回复
热议问题