Symbolic Signal Names

From CodeCodex

It can be handy to display symbolic names to the user instead of integer codes. Here's how to create a mapping of signal codes to their names in Python:

import signal

SignalName = {}
for Name in dir(signal) :
  # collect symbolic names for all signals
    Value = getattr(signal, Name)
    if Name.startswith("SIG") and type(Value) == int :
        SignalName[Value] = Name
    #end if
#end for

And here's an example of how to use it. Assume you have a child process termination value ChildStatus, for example set by

ChildStatus = os.waitpid(ChildPid, 0)[1]

Then you can do the usual check for whether the child process was terminated by a signal, with added display of a symbolic name for the signal if one can be found:

if os.WIFSIGNALED(ChildStatus) :
    SigValue = os.WTERMSIG(ChildStatus)
    SigName = SignalName.get(SigValue, "?")
    sys.stderr.write("Child died from signal %d (%s)\n" % (SigValue, SigName))
#end if

which might produce an output message like

Child died from signal 15 (SIGTERM)

A similar trick can be used, for instance, to get symbolic names for error codes from the errno module.