从 Python 中的数字获取信号名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2549939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:54:31  来源:igfitidea点击:

Get signal names from numbers in Python

pythonsignals

提问by Brian M. Hunt

Is there a way to map a signal number (e.g. signal.SIGINT) to its respective name (i.e. "SIGINT")?

有没有办法将信号编号(例如signal.SIGINT)映射到其各自的名称(即“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.:

我希望能够在收到信号时在日志中打印信号的名称,但是我无法在 Python 中找到从信号编号到名称的映射,即:

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:

对于某些字典 sig_names,因此当进程收到 SIGINT 时,它会打印:

Received signal (SIGINT)

采纳答案by Wolph

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

没有,但如果你不介意一点点hack,你可以像这样生成它:

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

回答by pR0Ps

With the addition of the signal.Signalsenumin Python 3.5 this is now as easy as:

随着Python 3.5 中的添加,这现在很简单:signal.Signalsenum

>>> import signal
>>> signal.SIGINT.name
'SIGINT'
>>> signal.SIGINT.value
2
>>> signal.Signals(2).name
'SIGINT'
>>> signal.Signals['SIGINT'].value
2

回答by devin_s

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

Python Standard Library By Example 在信号一章中展示了这个函数:

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]

回答by ssc

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.

可能有一个不需要 tuple(...)[0] 位的符号,但我似乎无法弄清楚。

回答by Daniel G

Well, help(signal)says at the bottom:

好吧,help(signal)在底部说:

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

回答by Roger Pate

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

回答by Roger Pate

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

对于signal_value正数(信号数)或负值(子进程的返回状态):

import signal

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