Python - Trap all signals

Justin Ethier picture Justin Ethier · Jan 27, 2010 · Viewed 32.7k times · Source

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?

Answer

Noufal Ibrahim picture Noufal Ibrahim · Jan 27, 2010

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