<div dir="ltr">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: <div><a href="http://grodola.blogspot.com/2016/02/how-to-always-execute-exit-functions-in-py.html">http://grodola.blogspot.com/2016/02/how-to-always-execute-exit-functions-in-py.html</a> </div></div><div class="gmail_extra"><br><div class="gmail_quote">On Fri, Jan 20, 2017 at 1:46 PM, Thomas Kluyver <span dir="ltr"><<a href="mailto:thomas@kluyver.me.uk" target="_blank">thomas@kluyver.me.uk</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">Not uncommonly, I want to do something like this in code:<br>
<br>
import signal<br>
<br>
# Install my own signal handler<br>
prev_hup = signal.signal(signal.SIGHUP, my_handler)<br>
prev_term = signal.signal(signal.SIGTERM, my_handler)<br>
try:<br>
do_something_else()<br>
finally:<br>
# Restore previous signal handlers<br>
signal.signal(signal.SIGHUP, prev_hup)<br>
signal.signal(signal.SIGTERM, prev_term)<br>
<br>
This works if the existing signal handler is a Python function, or the<br>
special values SIG_IGN (ignore) or SIG_DFL (default). However, it breaks<br>
if code has set a signal handler in C: this is not returned, and there<br>
is no way in Python to reinstate a C-level signal handler once we've<br>
replaced it from Python.<br>
<br>
I propose two possible solutions:<br>
<br>
1. The high-level approach: a context manager which can temporarily set<br>
one or more signal handlers. If this was implemented in C, it could<br>
restore C-level as well as Python-level signal handlers.<br>
<br>
2. A lower level approach: signal() and getsignal() would gain the<br>
ability to return an opaque object which refers to a C-level signal<br>
handler. The only use for this would be to pass it back to<br>
signal.signal() to set it as a signal handler again. The context manager<br>
from (1) could then be implemented in Python.<br>
<br>
Crosslinking <a href="http://bugs.python.org/issue13285" rel="noreferrer" target="_blank">http://bugs.python.org/<wbr>issue13285</a><br>
<br>
Thomas<br>
______________________________<wbr>_________________<br>
Python-ideas mailing list<br>
<a href="mailto:Python-ideas@python.org">Python-ideas@python.org</a><br>
<a href="https://mail.python.org/mailman/listinfo/python-ideas" rel="noreferrer" target="_blank">https://mail.python.org/<wbr>mailman/listinfo/python-ideas</a><br>
Code of Conduct: <a href="http://python.org/psf/codeofconduct/" rel="noreferrer" target="_blank">http://python.org/psf/<wbr>codeofconduct/</a><br>
</blockquote></div><br><br clear="all"><div><br></div>-- <br><div class="gmail_signature" data-smartmail="gmail_signature"><div dir="ltr"><div>Giampaolo - <a href="http://grodola.blogspot.com" target="_blank">http://grodola.blogspot.com</a></div><div><br></div></div></div>
</div>