Finding name for a signal number

Michael Hudson mwh at python.net
Tue Nov 6 08:39:31 EST 2001


Oliver Fromme <olli at secnetix.de> writes:

[schnipp]
> The next thing I came up with is extracting the signal
> names from the namespace dictionary of the signal module
> itself, like this:
> 
>     import signal
>     
>     def get_signame (n):
>         "Return the signal name for a signal number."
>         for sig in dir(signal):
>             if sig.startswith("SIG"):
>                 value = eval("signal." + sig)
>                 if type(value) is IntType and value == n:
>                     return sig
>         return "SIG#" + str(n)
> 
> This works.  However, the above code seems awkward and
> inefficient, in particular the eval() part.  Is there a
> better way?  Did I miss something?

Yes: getattr.

Also your logic seems a touch backwards - why search through the
module every time?

I'd do something like this:

def getsigdict():
    import signal
    r = {}
    for name in dir(signal):
        if name.startswith("SIG"):
           r[name] = getattr(signal, name)
    return r

sigdict = getsigdict()

Cheers,
M.

-- 
  In many ways, it's a dull language, borrowing solid old concepts
  from many other languages & styles:  boring syntax, unsurprising
  semantics, few  automatic coercions, etc etc.  But that's one of
  the things I like about it.                 -- Tim Peters, 16 Sep 93



More information about the Python-list mailing list