Brian M. Hunt
Brian M. Hunt

Reputation: 83818

Get signal names from numbers in Python

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)

Upvotes: 73

Views: 25609

Answers (8)

PiranhaPhish
PiranhaPhish

Reputation: 185

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'

Upvotes: 13

user6331769
user6331769

Reputation:

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')

Upvotes: 0

pR0Ps
pR0Ps

Reputation: 2792

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

Upvotes: 130

None
None

Reputation: 2594

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

Upvotes: 0

Wolph
Wolph

Reputation: 80031

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_'))

Upvotes: 35

devin_s
devin_s

Reputation: 3405

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]

Upvotes: 12

ssc
ssc

Reputation: 9883

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.

Upvotes: 3

Daniel G
Daniel G

Reputation: 69682

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"}

Upvotes: 1

Related Questions