Get signal names from numbers in Python

Question:

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)
Asked By: Brian M. Hunt

||

Answers:

There is none, but if you don’t mind a little hack, you can generate it like this:

import signal
dict((k, v) for v, k in reversed(sorted(signal.__dict__.items()))
     if v.startswith('SIG') and not v.startswith('SIG_'))
Answered By: Wolph

Well, help(signal) says at the bottom:

DATA
    NSIG = 23
    SIGABRT = 22
    SIGBREAK = 21
    SIGFPE = 8
    SIGILL = 4
    SIGINT = 2
    SIGSEGV = 11
    SIGTERM = 15
    SIG_DFL = 0
    SIG_IGN = 1

So this should work:

sig_names = {23:"NSIG", 22:"SIGABRT", 21:"SIGBREAK", 8:"SIGFPE", 4:"SIGILL",
             2:"SIGINT", 11:"SIGSEGV", 15:"SIGTERM", 0:"SIG_DFL", 1:"SIG_IGN"}
Answered By: Daniel G

I found this article when I was in the same situation and figured the handler is only handling one signal at a time, so I don’t even need a whole dictionary, just the name of one signal:

sig_name = tuple((v) for v, k in signal.__dict__.iteritems() if k == signum)[0]

there’s probably a notation that doesn’t need the tuple(…)[0] bit, but I can’t seem to figure it out.

Answered By: ssc

The Python Standard Library By Example shows this function in the chapter on signals:

SIGNALS_TO_NAMES_DICT = dict((getattr(signal, n), n) 
    for n in dir(signal) if n.startswith('SIG') and '_' not in n )

You can then use it like this:

print "Terminated by signal %s" % SIGNALS_TO_NAMES_DICT[signal_number]
Answered By: devin_s

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
Answered By: pR0Ps

Building on another answer:

import signal

if hasattr(signal, "Signals"):
    def _signal_name(signum):
        try:
            return signal.Signals(signum).name
        except ValueError:
            pass
else:
    def _signal_name(signum):
        for n, v in sorted(signal.__dict__.items()):
            if v != signum:
                continue
            if n.startswith("SIG") and not n.startswith("SIG_"):
                return n

def signal_name(signum):
    if signal.SIGRTMIN <= signum <= signal.SIGRTMAX:
        return "SIGRTMIN+{}".format(signum - signal.SIGRTMIN)
    x = _signal_name(signum)
    if x is None:
        # raise ValueError for invalid signals
        signal.getsignal(signum)
        x = "<signal {}>".format(signum)
    return x
Answered By: Roger Pate

for signal_value of positive number (signal number), or negative value (return status from subprocess):

import signal

signal_name = {
        getattr(signal, _signame): _signame
        for _signame in dir(signal)
        if _signame.startswith('SIG')
    }.get(abs(signal_value), 'Unknown')
Answered By: user6331769

As of Python 3.8, you can now use the signal.strsignal() method to return a textual description of the signal:

>>> signal.strsignal(signal.SIGTERM)
'Terminated'

>>> signal.strsignal(signal.SIGKILL)
'Killed'
Answered By: PiranhaPhish
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.