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