2000-06-28 23:07:31 +08:00
|
|
|
"""
|
|
|
|
atexit.py - allow programmer to define multiple exit functions to be executed
|
|
|
|
upon normal program termination.
|
|
|
|
|
2001-01-15 02:09:23 +08:00
|
|
|
One public function, register, is defined.
|
2000-06-28 23:07:31 +08:00
|
|
|
"""
|
|
|
|
|
2001-01-21 03:54:20 +08:00
|
|
|
__all__ = ["register"]
|
|
|
|
|
2000-06-28 23:07:31 +08:00
|
|
|
_exithandlers = []
|
|
|
|
def _run_exitfuncs():
|
|
|
|
"""run any registered exit functions
|
|
|
|
|
|
|
|
_exithandlers is traversed in reverse order so functions are executed
|
|
|
|
last in, first out.
|
|
|
|
"""
|
2001-01-15 02:09:23 +08:00
|
|
|
|
2000-06-28 23:07:31 +08:00
|
|
|
while _exithandlers:
|
2001-01-21 11:40:37 +08:00
|
|
|
func, targs, kargs = _exithandlers.pop()
|
2003-02-28 04:14:51 +08:00
|
|
|
func(*targs, **kargs)
|
2000-06-28 23:07:31 +08:00
|
|
|
|
|
|
|
def register(func, *targs, **kargs):
|
|
|
|
"""register a function to be executed upon normal program termination
|
|
|
|
|
|
|
|
func - function to be called at exit
|
|
|
|
targs - optional arguments to pass to func
|
|
|
|
kargs - optional keyword arguments to pass to func
|
|
|
|
"""
|
|
|
|
_exithandlers.append((func, targs, kargs))
|
|
|
|
|
|
|
|
import sys
|
2002-07-17 03:30:59 +08:00
|
|
|
if hasattr(sys, "exitfunc"):
|
|
|
|
# Assume it's another registered exit function - append it to our list
|
|
|
|
register(sys.exitfunc)
|
|
|
|
sys.exitfunc = _run_exitfuncs
|
|
|
|
|
2000-06-28 23:07:31 +08:00
|
|
|
del sys
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
def x1():
|
|
|
|
print "running x1"
|
|
|
|
def x2(n):
|
2004-02-13 01:35:32 +08:00
|
|
|
print "running x2(%r)" % (n,)
|
2000-06-28 23:07:31 +08:00
|
|
|
def x3(n, kwd=None):
|
2004-02-13 01:35:32 +08:00
|
|
|
print "running x3(%r, kwd=%r)" % (n, kwd)
|
2000-06-28 23:07:31 +08:00
|
|
|
|
|
|
|
register(x1)
|
|
|
|
register(x2, 12)
|
|
|
|
register(x3, 5, "bar")
|
|
|
|
register(x3, "no kwd args")
|