blob: a31163094f8e4e17e0847f2cd863e854155296c0 [file] [log] [blame]
Fred Drakec19425d2000-06-28 15:07:31 +00001"""
2atexit.py - allow programmer to define multiple exit functions to be executed
3upon normal program termination.
4
5One public function, register, is defined.
6"""
7
8_exithandlers = []
9def _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 """
15
16 while _exithandlers:
17 func, targs, kargs = _exithandlers[-1]
18 apply(func, targs, kargs)
19 _exithandlers.remove(_exithandlers[-1])
20
21def 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
30import sys
31try:
32 x = sys.exitfunc
33except AttributeError:
34 sys.exitfunc = _run_exitfuncs
35else:
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)
40del sys
41
42if __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")
54