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