blob: 85ccb248e4c5b3b94cd95c5bf5aa364f180e77f1 [file] [log] [blame]
Fred Drakec19425d2000-06-28 15:07:31 +00001"""
2atexit.py - allow programmer to define multiple exit functions to be executed
3upon normal program termination.
4
Tim Peters146965a2001-01-14 18:09:23 +00005One public function, register, is defined.
Fred Drakec19425d2000-06-28 15:07:31 +00006"""
7
Skip Montanaroe99d5ea2001-01-20 19:54:20 +00008__all__ = ["register"]
9
Fred Drakec19425d2000-06-28 15:07:31 +000010_exithandlers = []
11def _run_exitfuncs():
12 """run any registered exit functions
13
14 _exithandlers is traversed in reverse order so functions are executed
15 last in, first out.
16 """
Tim Peters146965a2001-01-14 18:09:23 +000017
Fred Drakec19425d2000-06-28 15:07:31 +000018 while _exithandlers:
Tim Peters384fd102001-01-21 03:40:37 +000019 func, targs, kargs = _exithandlers.pop()
Guido van Rossum68468eb2003-02-27 20:14:51 +000020 func(*targs, **kargs)
Fred Drakec19425d2000-06-28 15:07:31 +000021
22def register(func, *targs, **kargs):
23 """register a function to be executed upon normal program termination
24
25 func - function to be called at exit
26 targs - optional arguments to pass to func
27 kargs - optional keyword arguments to pass to func
28 """
29 _exithandlers.append((func, targs, kargs))
30
31import sys
Tim Peters012b69c2002-07-16 19:30:59 +000032if hasattr(sys, "exitfunc"):
33 # Assume it's another registered exit function - append it to our list
34 register(sys.exitfunc)
35sys.exitfunc = _run_exitfuncs
36
Fred Drakec19425d2000-06-28 15:07:31 +000037del sys
38
39if __name__ == "__main__":
40 def x1():
41 print "running x1"
42 def x2(n):
Walter Dörwald70a6b492004-02-12 17:35:32 +000043 print "running x2(%r)" % (n,)
Fred Drakec19425d2000-06-28 15:07:31 +000044 def x3(n, kwd=None):
Walter Dörwald70a6b492004-02-12 17:35:32 +000045 print "running x3(%r, kwd=%r)" % (n, kwd)
Fred Drakec19425d2000-06-28 15:07:31 +000046
47 register(x1)
48 register(x2, 12)
49 register(x3, 5, "bar")
50 register(x3, "no kwd args")