Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get signal names from numbers in Python

Tags:

python

signals

Is there a way to map a signal number (e.g. signal.SIGINT) to its respective name (i.e. "SIGINT")?

I'd like to be able to print the name of a signal in the log when I receive it, however I cannot find a map from signal numbers to names in Python, i.e.:

import signal def signal_handler(signum, frame):     logging.debug("Received signal (%s)" % sig_names[signum])  signal.signal(signal.SIGINT, signal_handler) 

For some dictionary sig_names, so when the process receives SIGINT it prints:

Received signal (SIGINT) 
like image 721
Brian M. Hunt Avatar asked Mar 31 '10 01:03

Brian M. Hunt


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


1 Answers

With the addition of the signal.Signals enum in Python 3.5 this is now as easy as:

>>> import signal >>> signal.SIGINT.name 'SIGINT' >>> signal.SIGINT.value 2 >>> signal.Signals(2).name 'SIGINT' >>> signal.Signals['SIGINT'].value 2 
like image 109
pR0Ps Avatar answered Oct 02 '22 07:10

pR0Ps