blob: 9d0b48c06b188e6ee56bdd1f085917a8922d5419 [file] [log] [blame]
Fred Drakec19425d2000-06-28 15:07:31 +00001\section{\module{atexit} ---
2 exit handlers}
3
4\declaremodule{standard}{atexit}
5\moduleauthor{Skip Montanaro}{skip@mojam.com}
6\sectionauthor{Skip Montanaro}{skip@mojam.com}
7\modulesynopsis{Register and execute cleanup functions.}
8
9The \module{atexit} module defines a single function to register
10cleanup functions. Functions thus registered are automatically
11executed upon normal interpreter termination.
12
13Note: the functions registered via this module are not called when the program is killed by a
14signal, when a Python fatal internal error is detected, or when
15\code{os._exit()} is called.
16
17This is an alternate interface to the functionality provided by the
18\code{sys.exitfunc} variable.
19\withsubitem{(in sys)}{\ttindex{exitfunc}}
20
21\begin{funcdesc}{register}{func\optional{, *args\optional{, **kargs}}}
22Register \var{func} as a function to be executed at termination. Any
23optional arguments that are to be passed to \var{func} must be passed
24as arguments to \function{register()}.
25
26At normal program termination (for instance, if
27\function{sys.exit()} is called or the main module's execution
28completes), all functions registered are called in last in, first out
29order. The assumption is that lower level modules will normally be
30imported before higher level modules and thus must be cleaned up
31later.
32\end{funcdesc}
33
34
35\subsection{\module{atexit} Example \label{atexit-example}}
36
37The following simple example demonstrates how a module can initialize
38a counter from a file when it is imported and save the counter's
39updated value automatically when the program terminates without
40relying on the application making an explicit call into this module at
41termination.
42
43\begin{verbatim}
44try:
45 _count = int(open("/tmp/counter").read())
46except IOError:
47 _count = 0
48
49def incrcounter(n):
50 global _count
51 _count = _count + n
52
53def savecounter():
54 open("/tmp/counter", "w").write("%d" % _count)
55
56import atexit
57atexit.register(savecounter)
58\end{verbatim}
59