python2atexit.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. """Uses the old atexit with added unregister for python 2.x
  2. and the new atexit for python 3.x
  3. """
  4. import atexit
  5. import sys
  6. __all__ = ["register", "unregister"]
  7. _exithandlers = []
  8. def _run_exitfuncs():
  9. """run any registered exit functions
  10. _exithandlers is traversed in reverse order so functions are executed
  11. last in, first out.
  12. """
  13. exc_info = None
  14. while _exithandlers:
  15. func, targs, kargs = _exithandlers.pop()
  16. try:
  17. func(*targs, **kargs)
  18. except SystemExit:
  19. exc_info = sys.exc_info()
  20. except:
  21. import traceback
  22. sys.stderr.write("Error in atexit._run_exitfuncs:\n")
  23. traceback.print_exc()
  24. exc_info = sys.exc_info()
  25. if exc_info is not None:
  26. raise exc_info[0](exc_info[1])
  27. def register(func, *targs, **kargs):
  28. """register a function to be executed upon normal program termination
  29. func - function to be called at exit
  30. targs - optional arguments to pass to func
  31. kargs - optional keyword arguments to pass to func
  32. func is returned to facilitate usage as a decorator.
  33. """
  34. if hasattr(atexit, "unregister"):
  35. atexit.register(func, *targs, **kargs)
  36. else:
  37. _exithandlers.append((func, targs, kargs))
  38. return func
  39. def unregister(func):
  40. """remove func from the list of functions that are registered
  41. doesn't do anything if func is not found
  42. func = function to be unregistered
  43. """
  44. if hasattr(atexit, "unregister"):
  45. atexit.unregister(func)
  46. else:
  47. handler_entries = [e for e in _exithandlers if e[0] == func]
  48. for e in handler_entries:
  49. _exithandlers.remove(e)
  50. if not hasattr(atexit, "unregister"):
  51. # Only in python 2.x
  52. atexit.register(_run_exitfuncs)