Search code examples
pythonlinuxsignal-handling

Python - Trap all signals


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, handleSigTERM)    

Is there any way to setup a handler for all signals received by the process, other than just setting them up one-at-a-time?


Solution

  • You could just loop through the signals in the signal module and set them up.

    for i in [x for x in dir(signal) if x.startswith("SIG")]:
      try:
        signum = getattr(signal,i)
        signal.signal(signum,sighandler)
      except (OSError, RuntimeError) as m: #OSError for Python3, RuntimeError for 2
        print ("Skipping {}".format(i))