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 | |
Skip Montanaro | e99d5ea | 2001-01-20 19:54:20 +0000 | [diff] [blame] | 8 | __all__ = ["register"] |
| 9 | |
Fred Drake | c19425d | 2000-06-28 15:07:31 +0000 | [diff] [blame] | 10 | _exithandlers = [] |
| 11 | def _run_exitfuncs(): |
| 12 | """run any registered exit functions |
| 13 | |
| 14 | _exithandlers is traversed in reverse order so functions are executed |
| 15 | last in, first out. |
| 16 | """ |
Tim Peters | 146965a | 2001-01-14 18:09:23 +0000 | [diff] [blame] | 17 | |
Fred Drake | c19425d | 2000-06-28 15:07:31 +0000 | [diff] [blame] | 18 | while _exithandlers: |
Tim Peters | 384fd10 | 2001-01-21 03:40:37 +0000 | [diff] [blame] | 19 | func, targs, kargs = _exithandlers.pop() |
Fred Drake | c19425d | 2000-06-28 15:07:31 +0000 | [diff] [blame] | 20 | apply(func, targs, kargs) |
Fred Drake | c19425d | 2000-06-28 15:07:31 +0000 | [diff] [blame] | 21 | |
| 22 | def register(func, *targs, **kargs): |
| 23 | """register a function to be executed upon normal program termination |
| 24 | |
| 25 | func - function to be called at exit |
| 26 | targs - optional arguments to pass to func |
| 27 | kargs - optional keyword arguments to pass to func |
| 28 | """ |
| 29 | _exithandlers.append((func, targs, kargs)) |
| 30 | |
| 31 | import sys |
Tim Peters | 012b69c | 2002-07-16 19:30:59 +0000 | [diff] [blame] | 32 | if hasattr(sys, "exitfunc"): |
| 33 | # Assume it's another registered exit function - append it to our list |
| 34 | register(sys.exitfunc) |
| 35 | sys.exitfunc = _run_exitfuncs |
| 36 | |
Fred Drake | c19425d | 2000-06-28 15:07:31 +0000 | [diff] [blame] | 37 | del sys |
| 38 | |
| 39 | if __name__ == "__main__": |
| 40 | def x1(): |
| 41 | print "running x1" |
| 42 | def x2(n): |
| 43 | print "running x2(%s)" % `n` |
| 44 | def x3(n, kwd=None): |
| 45 | print "running x3(%s, kwd=%s)" % (`n`, `kwd`) |
| 46 | |
| 47 | register(x1) |
| 48 | register(x2, 12) |
| 49 | register(x3, 5, "bar") |
| 50 | register(x3, "no kwd args") |