Context manager to temporarily set signal handlers

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

I don't know if this is related (regarding functions registered in C) but one problem I often have is to always execute exit functions. I have come up with this: http://grodola.blogspot.com/2016/02/how-to-always-execute-exit-functions-in-... On Fri, Jan 20, 2017 at 1:46 PM, Thomas Kluyver <thomas@kluyver.me.uk> wrote:
-- Giampaolo - http://grodola.blogspot.com

I don't know if this is related (regarding functions registered in C) but one problem I often have is to always execute exit functions. I have come up with this: http://grodola.blogspot.com/2016/02/how-to-always-execute-exit-functions-in-... On Fri, Jan 20, 2017 at 1:46 PM, Thomas Kluyver <thomas@kluyver.me.uk> wrote:
-- Giampaolo - http://grodola.blogspot.com
participants (2)
-
Giampaolo Rodola'
-
Thomas Kluyver