1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 """
26 Extend the behaviour of the default *atexit* module to support:
27
28 1) automatically catching of the (possible) exceptions thrown by exit function
29
30 2) exit function prioritization (lower value means higher priority)
31 E.g:
32 import atexit
33 atexit.register((<PRIORITY>,myfunc),args)
34
35 The backward-compatibility is kept so the existing code using :
36 import atexit
37 atexit.register(myfunc,args)
38 registers the function with the lowest priority (sys.maxint)
39 """
40
41 import atexit
42
43 from Ganga.Utility.logging import getLogger,log_user_exception
44 logger = getLogger()
45
47 """run any registered exit functions
48
49 atexit._exithandlers is traversed based on the priority.
50 If no priority was registered for a given function
51 than the lowest priority is assumed (LIFO policy)
52
53 We keep the same functionality as in *atexit* bare module but
54 we run each exit handler inside a try..catch block to be sure all
55 the registered handlers are executed
56 """
57
58 def priority_cmp(f1,f2):
59 """
60 Sort the exit functions based on priority in reversed order
61 """
62
63 p1 = f1[0][0]
64 p2 = f2[0][0]
65
66 return cmp(p2,p1)
67
68 def add_priority(x):
69 """
70 add a default priority to the functions not defining one (default priority=sys.maxint)
71 return a list containg ((priority,func),*targs,*kargs) elements
72 """
73 import sys
74 func = x[0]
75 if type(func)==type(()) and len(x[0])==2:
76 return x
77 else:
78 new = [(sys.maxint,func)]
79 new.extend(x[1:])
80 return new
81
82 atexit._exithandlers = map(add_priority,atexit._exithandlers)
83 atexit._exithandlers.sort(priority_cmp)
84
85 while atexit._exithandlers:
86 (priority, func), targs, kargs = atexit._exithandlers.pop()
87 try:
88 func(*targs, **kargs)
89 except Exception,x:
90 s = 'Cannot run one of the exit handlers: %s ... Cause: %s' % (func.__name__,str(x))
91 logger.warning(s)
92
94 """
95 Install a new shutdown manager, by overriding metods from atexit module
96 """
97
98 atexit._run_exitfuncs = _ganga_run_exitfuncs
99
100
101
102 import sys
103 sys.exitfunc = atexit._run_exitfuncs
104
105
106
107
108
109
110
111
112
113
114