0

I'm trying to replace this ugly block:

import signal
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
signal.signal(signal.SIGQUIT, signal_handler)
signal.signal(signal.SIGILL, signal_handler)
signal.signal(signal.SIGPIPE, signal_handler)

with this:

import signal
for sig in (SIGINT, SIGTERM, SIGQUIT, SIGILL, SIGPIPE):
    signal.signal(sig, signal_handler)

Unfortunately python throws:

File "./mysuperfile.py", line 107, in <module>
   for sig in (SIGINT, SIGTERM, SIGQUIT, SIGILL, SIGPIPE):
       NameError: name 'SIGINT' is not defined

I also tried to do

from signal import signal, SIGINT, SIGTERM, SIGQUIT, SIGILL, SIGPIPE

.. but this throws:

  File "./mysuperfile.py", line 108, in <module>
    signal.signal(sig, signal_handler)
AttributeError: 'builtin_function_or_method' object has no attribute 'signal'

Question: what is the correct syntax?

Thank you!

4

2 回答 2

2

I would probably do:

import signal
for sig in ("SIGINT", "SIGTERM", "SIGQUIT", "SIGILL", "SIGPIPE"):
    sig = getattr(signal,sig)
    signal.signal(sig, signal_handler)

When you do a simple import signal, all of your signal handles can be found in the current namespace as signal.SIGNALNAME (e.g. signal.SIGQUIT). This is the same thing as:

for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGQUIT, ...):
    signal.signal(sig,signal_handler)

Of course, you can import them directly into your current namespace as you were trying:

from signal import signal, SIGINT, SIGTERM, SIGQUIT, SIGILL, SIGPIPE

But then the signal function is known as simply signal (not signal.signal) in the current namespace. So, using that import, you could do:

for sig in (SIGINT, SIGTERM, SIGQUIT, SIGILL, SIGPIPE):
    signal(sig, signal_handler)

However, I find that to be less clear. Is signal the module or the function? Maybe it isn't too hard to figure out (after all, you can't call a module), but the other way it's obvious immediately.

于 2013-03-31T00:26:08.037 回答
1

You can't import signal from itself, but you can import both separately.

import signal
from signal import SIGINT, SIGTERM, SIGQUIT, SIGILL, SIGPIPE
于 2013-03-31T00:23:52.417 回答