Python Glossary Русский

all Python 3atexitfunction

atexit.register()

exit handlers

Registers a function to run when the program exits normally; it also works as a decorator.

Syntax

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

Handlers run in reverse order of registration — after the program ends or sys.exit(). They do not run on os._exit(), on death by a signal (SIGKILL, or SIGTERM without a handler) or on a fatal error, so they cannot be the only way to save data. An exception in a handler is printed as 'Exception ignored' but does not change the exit code. As a decorator it only suits a function without arguments.

Examples

import atexit
@atexit.register
def goodbye():
    print('goodbye')  # → goodbye
atexit.register(print, 'зарегистрирован вторым, выполнится первым')
print('конец программы')  # → конец программы
import atexit, os
atexit.register(print, 'не будет напечатано')
print('выход через os._exit', flush=True)  # → выход через os._exit
os._exit(0)

See also

Open in the full glossarydocs.python.orgReport an inaccuracy