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 func is returned to facilitate usage as a decorator.
46 _exithandlers
.append((func
, targs
, kargs
))
49 if hasattr(sys
, "exitfunc"):
50 # Assume it's another registered exit function - append it to our list
51 register(sys
.exitfunc
)
52 sys
.exitfunc
= _run_exitfuncs
54 if __name__
== "__main__":
58 print "running x2(%r)" % (n
,)
60 print "running x3(%r, kwd=%r)" % (n
, kwd
)
64 register(x3
, 5, "bar")
65 register(x3
, "no kwd args")