[Python-ideas] Context manager to temporarily set signal handlers
Giampaolo Rodola'
g.rodola at gmail.com
Sun Jan 22 06:15:27 EST 2017
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-py.html
On Fri, Jan 20, 2017 at 1:46 PM, Thomas Kluyver <thomas at kluyver.me.uk>
wrote:
> 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
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
--
Giampaolo - http://grodola.blogspot.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170122/2a166cca/attachment.html>
More information about the Python-ideas
mailing list