Get signal names from numbers in Python

Brian M. Hunt picture Brian M. Hunt · Mar 31, 2010 · Viewed 16.3k times · Source

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)

Answer

pR0Ps picture pR0Ps · Mar 14, 2016

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