0001 """ 0002 atexit.py - allow programmer to define multiple exit functions to be executed 0003 upon normal program termination. 0004 0005 One public function, register, is defined. 0006 """ 0007 0008 __all__ = ["register"] 0009 0010 _exithandlers = [] 0011 def _run_exitfuncs(): 0012 """run any registered exit functions 0013 0014 _exithandlers is traversed in reverse order so functions are executed 0015 last in, first out. 0016 """ 0017 0018 while _exithandlers: 0019 func, targs, kargs = _exithandlers.pop() 0020 func(*targs, **kargs) 0021 0022 def register(func, *targs, **kargs): 0023 """register a function to be executed upon normal program termination 0024 0025 func - function to be called at exit 0026 targs - optional arguments to pass to func 0027 kargs - optional keyword arguments to pass to func 0028 """ 0029 _exithandlers.append((func, targs, kargs)) 0030 0031 import sys 0032 if hasattr(sys, "exitfunc"): 0033 # Assume it's another registered exit function - append it to our list 0034 register(sys.exitfunc) 0035 sys.exitfunc = _run_exitfuncs 0036 0037 del sys 0038 0039 if __name__ == "__main__": 0040 def x1(): 0041 print "running x1" 0042 def x2(n): 0043 print "running x2(%r)" % (n,) 0044 def x3(n, kwd=None): 0045 print "running x3(%r, kwd=%r)" % (n, kwd) 0046 0047 register(x1) 0048 register(x2, 12) 0049 register(x3, 5, "bar") 0050 register(x3, "no kwd args") 0051
Generated by PyXR 0.9.4