Fred Drake | c19425d | 2000-06-28 15:07:31 +0000 | [diff] [blame] | 1 | """ |
| 2 | atexit.py - allow programmer to define multiple exit functions to be executed |
| 3 | upon normal program termination. |
| 4 | |
Tim Peters | 146965a | 2001-01-14 18:09:23 +0000 | [diff] [blame] | 5 | One public function, register, is defined. |
Fred Drake | c19425d | 2000-06-28 15:07:31 +0000 | [diff] [blame] | 6 | """ |
| 7 | |
| 8 | _exithandlers = [] |
| 9 | def _run_exitfuncs(): |
| 10 | """run any registered exit functions |
| 11 | |
| 12 | _exithandlers is traversed in reverse order so functions are executed |
| 13 | last in, first out. |
| 14 | """ |
Tim Peters | 146965a | 2001-01-14 18:09:23 +0000 | [diff] [blame] | 15 | |
Fred Drake | c19425d | 2000-06-28 15:07:31 +0000 | [diff] [blame] | 16 | while _exithandlers: |
| 17 | func, targs, kargs = _exithandlers[-1] |
| 18 | apply(func, targs, kargs) |
| 19 | _exithandlers.remove(_exithandlers[-1]) |
| 20 | |
| 21 | def register(func, *targs, **kargs): |
| 22 | """register a function to be executed upon normal program termination |
| 23 | |
| 24 | func - function to be called at exit |
| 25 | targs - optional arguments to pass to func |
| 26 | kargs - optional keyword arguments to pass to func |
| 27 | """ |
| 28 | _exithandlers.append((func, targs, kargs)) |
| 29 | |
| 30 | import sys |
| 31 | try: |
| 32 | x = sys.exitfunc |
| 33 | except AttributeError: |
| 34 | sys.exitfunc = _run_exitfuncs |
| 35 | else: |
| 36 | # if x isn't our own exit func executive, assume it's another |
| 37 | # registered exit function - append it to our list... |
| 38 | if x != _run_exitfuncs: |
| 39 | register(x) |
| 40 | del sys |
| 41 | |
| 42 | if __name__ == "__main__": |
| 43 | def x1(): |
| 44 | print "running x1" |
| 45 | def x2(n): |
| 46 | print "running x2(%s)" % `n` |
| 47 | def x3(n, kwd=None): |
| 48 | print "running x3(%s, kwd=%s)" % (`n`, `kwd`) |
| 49 | |
| 50 | register(x1) |
| 51 | register(x2, 12) |
| 52 | register(x3, 5, "bar") |
| 53 | register(x3, "no kwd args") |