atexit — Exit handlers



Changed in version 3.7: When used with C-API subinterpreters, registered functions are local to the interpreter they were registered in.

atexit.register(func, *args, **kwargs)



If an exception is raised during execution of the exit handlers, a traceback is printed (unless SystemExit is raised) and the exception information is saved. After all exit handlers have had a chance to run, the last exception to be raised is re-raised.



Remove func from the list of functions to be run at interpreter shutdown. unregister() silently does nothing if func was not previously registered. If func has been registered more than once, every occurrence of that function in the atexit call stack will be removed. Equality comparisons (==) are used internally during unregistration, so function references do not need to have matching identities.

See also

Module readline

Useful example of atexit to read and write readline history files.

atexit Example


    with open('counterfile') as infile:
        _count = int(
except FileNotFoundError:
    _count = 0

def incrcounter(n):
    global _count
    _count = _count + n

def savecounter():
    with open('counterfile', 'w') as outfile:
        outfile.write('%d' % _count)

import atexit



def goodbye(name, adjective):
    print('Goodbye %s, it was %s to meet you.' % (name, adjective))

import atexit

atexit.register(goodbye, 'Donny', 'nice')
# or:

Usage as a decorator:

import atexit

def goodbye():
    print('You are now leaving the Python sector.')

This only works with functions that can be called without arguments.