Python - Trap all signals

前端 未结 8 1382
慢半拍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:29

    Works on Windows 10 and Python 3.7:

    import signal
    import time
    
    def sighandler(signal,frame):
        print("signal",sig,frame)
        return
    
    catchable_sigs = set(signal.Signals)
    for sig in catchable_sigs:
        try:
            signal.signal(sig, sighandler)
            print("Setting ",sig)
            print ("value {}".format(sig))
        except (ValueError, OSError, RuntimeError) as m:
            print("Skipping ",sig)
            print ("Value {}".format(sig))
    
    
    # press some keys or issue kill
    x = 0
    while x < 5:
        time.sleep(4)
        x += 1
    

    Results:

    Skipping  Signals.CTRL_C_EVENT
    Value 0
    Skipping  Signals.CTRL_BREAK_EVENT
    Value 1
    Setting  Signals.SIGINT
    value 2
    Setting  Signals.SIGILL
    value 4
    Setting  Signals.SIGFPE
    value 8
    Setting  Signals.SIGSEGV
    value 11
    Setting  Signals.SIGTERM
    value 15
    Setting  Signals.SIGBREAK
    value 21
    Setting  Signals.SIGABRT
    value 22
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题