home *** CD-ROM | disk | FTP | other *** search
/ PC World 2001 April / PCWorld_2001-04_cd.bin / Software / TemaCD / webclean / !!!python!!! / BeOpen-Python-2.0.exe / ATEXIT.PY < prev    next >
Encoding:
Python Source  |  2000-09-28  |  1.4 KB  |  55 lines

  1. """
  2. atexit.py - allow programmer to define multiple exit functions to be executed
  3. upon normal program termination.
  4.  
  5. One public function, register, is defined.  
  6. """
  7.  
  8. _exithandlers = []
  9. def _run_exitfuncs():
  10.     """run any registered exit functions
  11.  
  12.     _exithandlers is traversed in reverse order so functions are executed
  13.     last in, first out.
  14.     """
  15.     
  16.     while _exithandlers:
  17.         func, targs, kargs = _exithandlers[-1]
  18.         apply(func, targs, kargs)
  19.         _exithandlers.remove(_exithandlers[-1])
  20.  
  21. def register(func, *targs, **kargs):
  22.     """register a function to be executed upon normal program termination
  23.  
  24.     func - function to be called at exit
  25.     targs - optional arguments to pass to func
  26.     kargs - optional keyword arguments to pass to func
  27.     """
  28.     _exithandlers.append((func, targs, kargs))
  29.  
  30. import sys
  31. try:
  32.     x = sys.exitfunc
  33. except AttributeError:
  34.     sys.exitfunc = _run_exitfuncs
  35. else:
  36.     # if x isn't our own exit func executive, assume it's another
  37.     # registered exit function - append it to our list...
  38.     if x != _run_exitfuncs:
  39.         register(x)
  40. del sys
  41.  
  42. if __name__ == "__main__":
  43.     def x1():
  44.         print "running x1"
  45.     def x2(n):
  46.         print "running x2(%s)" % `n`
  47.     def x3(n, kwd=None):
  48.         print "running x3(%s, kwd=%s)" % (`n`, `kwd`)
  49.  
  50.     register(x1)
  51.     register(x2, 12)
  52.     register(x3, 5, "bar")
  53.     register(x3, "no kwd args")
  54.  
  55.