2 atexit.py - allow programmer to define multiple exit functions to be executed
3 upon normal program termination.
5 One public function, register, is defined.
14 """run any registered exit functions
16 _exithandlers is traversed in reverse order so functions are executed
22 func, targs, kargs = _exithandlers.pop()
26 exc_info = sys.exc_info()
29 print >> sys.stderr, "Error in atexit._run_exitfuncs:"
31 exc_info = sys.exc_info()
33 if exc_info is not None:
34 raise exc_info[0], exc_info[1], exc_info[2]
37 def register(func, *targs, **kargs):
38 """register a function to be executed upon normal program termination
40 func - function to be called at exit
41 targs - optional arguments to pass to func
42 kargs - optional keyword arguments to pass to func
44 _exithandlers.append((func, targs, kargs))
46 if hasattr(sys, "exitfunc"):
47 # Assume it's another registered exit function - append it to our list
48 register(sys.exitfunc)
49 sys.exitfunc = _run_exitfuncs
51 if __name__ == "__main__":
55 print "running x2(%r)" % (n,)
57 print "running x3(%r, kwd=%r)" % (n, kwd)
61 register(x3, 5, "bar")
62 register(x3, "no kwd args")