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.,At normal program termination (for instance, if sys.exit() is called or the main module’s execution completes), all functions registered are called in last in, first out order. The assumption is that lower level modules will normally be imported before higher level modules and thus must be cleaned up later.,Register func as a function to be executed at termination. Any optional arguments that are to be passed to func must be passed as arguments to register(). It is possible to register the same function and arguments more than once.,The following simple example demonstrates how a module can initialize a counter from a file when it is imported and save the counter’s updated value automatically when the program terminates without relying on the application making an explicit call into this module at termination.
try:
with open('counterfile') as infile:
_count = int(infile.read())
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
atexit.register(savecounter)
def goodbye(name, adjective):
print('Goodbye %s, it was %s to meet you.' % (name, adjective))
import atexit
atexit.register(goodbye, 'Donny', 'nice')
# or:
atexit.register(goodbye, adjective = 'nice', name = 'Donny')
import atexit
@atexit.register
def goodbye():
print('You are now leaving the Python sector.')
import atexit
def all_done():
print('all_done()')
print('Registering')
atexit.register(all_done)
print('Registered')
$ python3 atexit_simple.py Registering Registered all_done()
import atexit
def my_cleanup(name):
print('my_cleanup({})'.format(name))
atexit.register(my_cleanup, 'first')
atexit.register(my_cleanup, 'second')
atexit.register(my_cleanup, 'third')
$ python3 atexit_multiple.py my_cleanup(third) my_cleanup(second) my_cleanup(first)
import atexit
@atexit.register
def all_done():
print('all_done()')
print('starting main program')
$ python3 atexit_decorator.py starting main program all_done()
If an exception occurs while the exit handlers are being executed, a traceback is produced and the exception information is preserved. The final exception to be raised is re-raised once all exit handlers have had a chance to run.,The same function can be registered as exit handlers multiple times.,The register() method registers the given function to be executed at termination. This method also accepts the arguments that need to be passed to the given function.,The functions registered via this module are not executed when a program is terminated by a signal that is not handled by Python, when os.exit() is called, or when Python fatal internal error is detected. Thee handlers or functions are executed in reverse order with reference to the order in which they were registered.
The given function can also be registered using the @atexit.register
decorator. For example:
@atexit.register
def func_4():
print("Executing func_4 with no arguments")
Syntax
atexit.register(func, * args, ** kwargs)
import atexit
def func_1(args):
print("Executing func_1 with argument - %s" % (args, ))
def func_2():
print("Executing func_2 with no arguments")
def func_3(arg1, arg2):
print("Executing func_3 with arg1 - %s, arg2 - %s" % (arg1, arg2))
print("Hello Educative")
atexit.register(func_1, [1, 2, 3])
atexit.register(func_2)
atexit.register(func_3, arg1 = "hello", arg2 = "educative")
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.,At normal program termination (for instance, if sys.exit() is called or the main module’s execution completes), all functions registered are called in last in, first out order. The assumption is that lower level modules will normally be imported before higher level modules and thus must be cleaned up later.,Register func as a function to be executed at termination. Any optional arguments that are to be passed to func must be passed as arguments to register(). It is possible to register the same function and arguments more than once.,The following simple example demonstrates how a module can initialize a counter from a file when it is imported and save the counter’s updated value automatically when the program terminates without relying on the application making an explicit call into this module at termination.
try:
with open("counterfile") as infile:
_count = int(infile.read())
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
atexit.register(savecounter)
def goodbye(name, adjective):
print('Goodbye, %s, it was %s to meet you.' % (name, adjective))
import atexit
atexit.register(goodbye, 'Donny', 'nice')
# or:
atexit.register(goodbye, adjective = 'nice', name = 'Donny')
import atexit
@atexit.register
def goodbye():
print("You are now leaving the Python sector.")
A function registered with atexit() throws an exception, and the exception is not handled. The following demonstrates this: ,The expression that is thrown also throws an exception, and that exception is not handled.,The constructor or destructor of a nonlocal static object throws an exception, and the exception is not handled.,During stack unwinding, a destructor throws an exception and that exception is not handled.
void terminate()
extern "C" printf(char* ...);
#include <exception>
#include <cstdlib>
using namespace std;
extern "C" void f() {
printf("Function f()\n");
throw "Exception thrown from f()";
}
extern "C" void g() { printf("Function g()\n"); }
extern "C" void h() { printf("Function h()\n"); }
void my_terminate() {
printf("Call to my_terminate\n");
abort();
}
int main() {
set_terminate(my_terminate);
atexit(f);
atexit(g);
atexit(h);
printf("In main\n");
}
In main
Function h()
Function g()
Function f()
Call to my_terminate