2000-06-28 17:07:31 +02:00
|
|
|
"""
|
|
|
|
atexit.py - allow programmer to define multiple exit functions to be executed
|
|
|
|
upon normal program termination.
|
|
|
|
|
2001-01-14 19:09:23 +01:00
|
|
|
One public function, register, is defined.
|
2000-06-28 17:07:31 +02:00
|
|
|
"""
|
|
|
|
|
2001-01-20 20:54:20 +01:00
|
|
|
__all__ = ["register"]
|
|
|
|
|
2004-12-11 03:49:40 +01:00
|
|
|
import sys
|
|
|
|
|
2000-06-28 17:07:31 +02: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-14 19:09:23 +01:00
|
|
|
|
2004-11-04 05:31:30 +01:00
|
|
|
exc_info = None
|
2000-06-28 17:07:31 +02:00
|
|
|
while _exithandlers:
|
2001-01-21 04:40:37 +01:00
|
|
|
func, targs, kargs = _exithandlers.pop()
|
2004-11-04 05:31:30 +01:00
|
|
|
try:
|
|
|
|
func(*targs, **kargs)
|
|
|
|
except SystemExit:
|
|
|
|
exc_info = sys.exc_info()
|
|
|
|
except:
|
2004-12-11 03:49:40 +01:00
|
|
|
import traceback
|
2004-11-04 05:31:30 +01:00
|
|
|
print >> sys.stderr, "Error in atexit._run_exitfuncs:"
|
|
|
|
traceback.print_exc()
|
|
|
|
exc_info = sys.exc_info()
|
|
|
|
|
|
|
|
if exc_info is not None:
|
|
|
|
raise exc_info[0], exc_info[1], exc_info[2]
|
|
|
|
|
2000-06-28 17:07:31 +02: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))
|
|
|
|
|
2002-07-16 21:30:59 +02: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 17:07:31 +02:00
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
def x1():
|
|
|
|
print "running x1"
|
|
|
|
def x2(n):
|
2004-02-12 18:35:32 +01:00
|
|
|
print "running x2(%r)" % (n,)
|
2000-06-28 17:07:31 +02:00
|
|
|
def x3(n, kwd=None):
|
2004-02-12 18:35:32 +01:00
|
|
|
print "running x3(%r, kwd=%r)" % (n, kwd)
|
2000-06-28 17:07:31 +02:00
|
|
|
|
|
|
|
register(x1)
|
|
|
|
register(x2, 12)
|
|
|
|
register(x3, 5, "bar")
|
|
|
|
register(x3, "no kwd args")
|