Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 850
Justin Ethier Avatar asked Jan 27 '10 17:01

Justin Ethier


People also ask

How do you catch signals in Python?

To catch a signal in Python, you need to register the signal you want to listen for and specify what function should be called when that signal is received. This example shows how to catch a SIGINT and exit gracefully.

What is SIGUSR1 in Python?

10 (SIGUSR1): user-defined signal. 11 (SIGSEGV): segmentation fault due to illegal access of a memory segment. 12 (SIGUSR2): user-defined signal. 13 (SIGPIPE): writing into a pipe, and nobody is reading from it. 14 (SIGALRM): the timer terminated (alarm)

What is SIGKILL in Python?

SIGKILL is where the Python process is terminated by your system. Reasons I have seen this: Low resources (not enough RAM, usually) - monitor and see how much the program is using. You might also want to try explicitly setting n_jobs to a low number, as CPU over-subscription could be an issue.

What is Sigterm in Python?

Python provides the Signal library allowing developers to catch Unix signals and set handlers for asynchronous events. For example, the 'SIGTERM' (Terminate) signal is received when issuing a 'kill' command for a given Unix process.


2 Answers

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)) 
like image 166
Noufal Ibrahim Avatar answered Sep 27 '22 21:09

Noufal Ibrahim


As of Python 3.5, the signal constants are defined as an enum, enabling a nicer approach:

import signal  catchable_sigs = set(signal.Signals) - {signal.SIGKILL, signal.SIGSTOP} for sig in catchable_sigs:     signal.signal(sig, print)  # Substitute handler of choice for `print` 
like image 24
doctaphred Avatar answered Sep 27 '22 21:09

doctaphred