Finding name for a signal number

Skip Montanaro skip at pobox.com
Tue Nov 6 08:49:14 EST 2001


    Oliver> In a small script I'd like to print the name of a signal number:
    Oliver> In the event that an os.system() call is aborted by a signal,
    Oliver> the signal number is returned in the lower 7 bits of the return
    Oliver> value.  I'd like to print a meaningful message which includes
    Oliver> the signal name (like "SIGQUIT"), not just the number.

    ...

    Oliver> The next thing I came up with is extracting the signal
    Oliver> names from the namespace dictionary of the signal module
    Oliver> itself, like this:

You are very close, but if you have to do this repeated, you probably don't
want to do it on-the-fly, just once ahead of tim.  As you noticed, the names
are there in the signal module, just not in quite the format you'd like.
Try something like the following to generate a dictionary that will map a
signal number back to its name:

    >>> import signal
    >>> for nm in dir(signal):
    ...   if nm.startswith("SIG"):
    ...     v = getattr(signal, nm)
    ...     if type(v) == type(1):
    ...       d[v] = nm
    ... 
    >>> d
    {0: 'SIG_DFL', 1: 'SIG_IGN', 2: 'SIGINT', 3: 'SIGQUIT', 4: 'SIGILL',
     5: 'SIGTRAP', 6: 'SIGIOT', 7: 'SIGBUS', 8: 'SIGFPE', 9: 'SIGKILL',
     10: 'SIGUSR1', 11: 'SIGSEGV', 12: 'SIGUSR2', 13: 'SIGPIPE', 14: 'SIGALRM',
     15: 'SIGTERM', 17: 'SIGCLD', 18: 'SIGCONT', 19: 'SIGSTOP', 20: 'SIGTSTP',
     21: 'SIGTTIN', 22: 'SIGTTOU', 23: 'SIGURG', 24: 'SIGXCPU', 25: 'SIGXFSZ',
     26: 'SIGVTALRM', 27: 'SIGPROF', 28: 'SIGWINCH', 29: 'SIGPOLL',
     30: 'SIGPWR', 31: 'SIGSYS'}

You can then use the dictionary in your get_signame function to map signals
to their names quickly.

-- 
Skip Montanaro (skip at pobox.com)
http://www.mojam.com/
http://www.musi-cal.com/




More information about the Python-list mailing list