[Python-ideas] Context manager to temporarily set signal handlers
Thomas Kluyver
thomas at kluyver.me.uk
Fri Jan 20 07:46:19 EST 2017
Not uncommonly, I want to do something like this in code:
import signal
# Install my own signal handler
prev_hup = signal.signal(signal.SIGHUP, my_handler)
prev_term = signal.signal(signal.SIGTERM, my_handler)
try:
do_something_else()
finally:
# Restore previous signal handlers
signal.signal(signal.SIGHUP, prev_hup)
signal.signal(signal.SIGTERM, prev_term)
This works if the existing signal handler is a Python function, or the
special values SIG_IGN (ignore) or SIG_DFL (default). However, it breaks
if code has set a signal handler in C: this is not returned, and there
is no way in Python to reinstate a C-level signal handler once we've
replaced it from Python.
I propose two possible solutions:
1. The high-level approach: a context manager which can temporarily set
one or more signal handlers. If this was implemented in C, it could
restore C-level as well as Python-level signal handlers.
2. A lower level approach: signal() and getsignal() would gain the
ability to return an opaque object which refers to a C-level signal
handler. The only use for this would be to pass it back to
signal.signal() to set it as a signal handler again. The context manager
from (1) could then be implemented in Python.
Crosslinking http://bugs.python.org/issue13285
Thomas
More information about the Python-ideas
mailing list