Python etc / atexit


The module atexit allows registering hooks that will be executed when the program terminates.

There are only a few cases when it is NOT executed:

  • When os._exit (don't confuse with sys.exit) is called.
  • When the interpreter failed with a fatal error.
  • When the process is hard-killed. For example, someone executed kill -9 or the system is ran out of memory.

In all other cases, like an unhandled exception or sys.exit, the registered hooks will be executed.

A few use cases:

  • Finish pending jobs
  • Send pending log messages into the log system
  • Save interactive interpreter history

However, keep in mind that there is no way to handle unhandled exceptions using atexit because it is executed after the exception is printed and discarded.

import atexit

atexit.register(print, 'FINISHED')


Traceback (most recent call last):
  File "", line 4, in <module>
ZeroDivisionError: division by zero