How to avoid overriding signal handlers in Python?

My experiment code is like:

import signal def hi(signum, frame): print "hi" signal.signal(signal.SIGINT, hi) signal.signal(signal.SIGINT, signal.SIG_IGN) 

hi did not print because the signal handler is overridden by signal.SIG_IGN .

How can i avoid this?

+4
source share
2 answers

If you do not want to override your own handler, make sure you install it:

 if signal.getsignal(signal.SIGINT) in [signal.SIG_IGN, signal.SIG_DFL]: signal.signal(signal.SIGINT, hi) 

According to the documentation , it is possible that some excellent process has already reassigned a default handler. If you do not want to override this, add None to the signal list.

The obvious wrapper for signal.signal(..., signal.SIG_IGN) is the not in test.

added in response to comment

Linking signal handlers are not often executed because the signals are so granular. If I really wanted to do this, I would run the atexit model and register the functions that will be called by your handler.

+2
source

You can try to check if there is already a handler. If so, put your desired handler and the old handler in a wrapper function that calls both of them.

 def append_signal(sig, f): old = None if callable(signal.getsignal(sig)): old = signal.getsignal(sig) def helper(*args, **kwargs): if old is not None: old(*args, **kwargs) f(*args, **kwargs) signal.signal(sig, helper) 
+1
source

All Articles