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?
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.
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)
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.
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.
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))
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`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With