]>
Commit | Line | Data |
---|---|---|
4710c53d | 1 | """\r |
2 | atexit.py - allow programmer to define multiple exit functions to be executed\r | |
3 | upon normal program termination.\r | |
4 | \r | |
5 | One public function, register, is defined.\r | |
6 | """\r | |
7 | \r | |
8 | __all__ = ["register"]\r | |
9 | \r | |
10 | import sys\r | |
11 | \r | |
12 | _exithandlers = []\r | |
13 | def _run_exitfuncs():\r | |
14 | """run any registered exit functions\r | |
15 | \r | |
16 | _exithandlers is traversed in reverse order so functions are executed\r | |
17 | last in, first out.\r | |
18 | """\r | |
19 | \r | |
20 | exc_info = None\r | |
21 | while _exithandlers:\r | |
22 | func, targs, kargs = _exithandlers.pop()\r | |
23 | try:\r | |
24 | func(*targs, **kargs)\r | |
25 | except SystemExit:\r | |
26 | exc_info = sys.exc_info()\r | |
27 | except:\r | |
28 | import traceback\r | |
29 | print >> sys.stderr, "Error in atexit._run_exitfuncs:"\r | |
30 | traceback.print_exc()\r | |
31 | exc_info = sys.exc_info()\r | |
32 | \r | |
33 | if exc_info is not None:\r | |
34 | raise exc_info[0], exc_info[1], exc_info[2]\r | |
35 | \r | |
36 | \r | |
37 | def register(func, *targs, **kargs):\r | |
38 | """register a function to be executed upon normal program termination\r | |
39 | \r | |
40 | func - function to be called at exit\r | |
41 | targs - optional arguments to pass to func\r | |
42 | kargs - optional keyword arguments to pass to func\r | |
43 | \r | |
44 | func is returned to facilitate usage as a decorator.\r | |
45 | """\r | |
46 | _exithandlers.append((func, targs, kargs))\r | |
47 | return func\r | |
48 | \r | |
49 | if hasattr(sys, "exitfunc"):\r | |
50 | # Assume it's another registered exit function - append it to our list\r | |
51 | register(sys.exitfunc)\r | |
52 | sys.exitfunc = _run_exitfuncs\r | |
53 | \r | |
54 | if __name__ == "__main__":\r | |
55 | def x1():\r | |
56 | print "running x1"\r | |
57 | def x2(n):\r | |
58 | print "running x2(%r)" % (n,)\r | |
59 | def x3(n, kwd=None):\r | |
60 | print "running x3(%r, kwd=%r)" % (n, kwd)\r | |
61 | \r | |
62 | register(x1)\r | |
63 | register(x2, 12)\r | |
64 | register(x3, 5, "bar")\r | |
65 | register(x3, "no kwd args")\r |