[Python-ideas] atexit.register_w_signals()

Giampaolo Rodola' g.rodola at gmail.com
Fri Feb 12 13:36:28 EST 2016

On Fri, Feb 12, 2016 at 7:11 PM, Ethan Furman <ethan at stoneleaf.us> wrote:

> On 02/12/2016 09:51 AM, Giampaolo Rodola' wrote:
> http://...
>> Thoughts?
> If you have an idea, please post that idea here, not a link.
> --
> ~Ethan~
> _______________________________________________
> 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/

Of course you are right, I'm sorry.
So, one problem with atexit.register() is that it won't run the registered
function in case the process is killed by a signal.

import atexit, os, signal
def cleanup():
    print("on exit")  # XXX this never gets printed
os.kill(os.getpid(), signal.SIGTERM)

The correct way to do that is to use signal.signal(). The problem with that
though is that in case a third-party module has
already registered a function for that signal, the new function will
overwrite the old one:

import os, signal

def old(*args):
    print("old")  # XXX this never gets printed

def new(*args):

signal.signal(signal.SIGTERM, old)
signal.signal(signal.SIGTERM, new)
os.kill(os.getpid(), signal.SIGTERM)

Also, we would still have to use atexit.register() so that the new function
is called also on "clean" interpreter exit and take into account other
signals other than SIGTERM which would cause the process to terminate
(SIGINT, etc.). My proposal is to evaluate adding a higher-level function
which takes care of all these details, providing better chances to execute
the exit function than atexit.register or signal.signal alone.
I also noticed that every time I end up working on a new code base, most of
the time people are using either atexit or signal module without knowing
these implications. It also took quite a bit to do the same and come up
with this code.


Relevant blog post:

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160212/14d543c8/attachment-0001.html>

More information about the Python-ideas mailing list