This repository has been archived by the owner on Mar 19, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
exceptionHandling.py
106 lines (82 loc) · 4.05 KB
/
exceptionHandling.py
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# -*- coding: utf-8 -*-
"""This module installs a wrapper around sys.excepthook which allows multiple
new exception handlers to be registered.
Optionally, the wrapper also stops exceptions from causing long-term storage
of local stack frames. This has two major effects:
- Unhandled exceptions will no longer cause memory leaks
(If an exception occurs while a lot of data is present on the stack,
such as when loading large files, the data would ordinarily be kept
until the next exception occurs. We would rather release this memory
as soon as possible.)
- Some debuggers may have a hard time handling uncaught exceptions
The module also provides a callback mechanism allowing others to respond
to exceptions.
"""
import sys, time
#from lib.Manager import logMsg
import traceback
#from log import *
#logging = False
callbacks = []
clear_tracebacks = False
def register(fn):
"""
Register a callable to be invoked when there is an unhandled exception.
The callback will be passed the output of sys.exc_info(): (exception type, exception, traceback)
Multiple callbacks will be invoked in the order they were registered.
"""
callbacks.append(fn)
def unregister(fn):
"""Unregister a previously registered callback."""
callbacks.remove(fn)
def setTracebackClearing(clear=True):
"""
Enable or disable traceback clearing.
By default, clearing is disabled and Python will indefinitely store unhandled exception stack traces.
This function is provided since Python's default behavior can cause unexpected retention of
large memory-consuming objects.
"""
global clear_tracebacks
clear_tracebacks = clear
class ExceptionHandler(object):
def __call__(self, *args):
## Start by extending recursion depth just a bit.
## If the error we are catching is due to recursion, we don't want to generate another one here.
recursionLimit = sys.getrecursionlimit()
try:
sys.setrecursionlimit(recursionLimit+100)
## call original exception handler first (prints exception)
global original_excepthook, callbacks, clear_tracebacks
try:
print("===== %s =====" % str(time.strftime("%Y.%m.%d %H:%m:%S", time.localtime(time.time()))))
except Exception:
sys.stderr.write("Warning: stdout is broken! Falling back to stderr.\n")
sys.stdout = sys.stderr
ret = original_excepthook(*args)
for cb in callbacks:
try:
cb(*args)
except Exception:
print(" --------------------------------------------------------------")
print(" Error occurred during exception callback %s" % str(cb))
print(" --------------------------------------------------------------")
traceback.print_exception(*sys.exc_info())
## Clear long-term storage of last traceback to prevent memory-hogging.
## (If an exception occurs while a lot of data is present on the stack,
## such as when loading large files, the data would ordinarily be kept
## until the next exception occurs. We would rather release this memory
## as soon as possible.)
if clear_tracebacks is True:
sys.last_traceback = None
finally:
sys.setrecursionlimit(recursionLimit)
def implements(self, interface=None):
## this just makes it easy for us to detect whether an ExceptionHook is already installed.
if interface is None:
return ['ExceptionHandler']
else:
return interface == 'ExceptionHandler'
## replace built-in excepthook only if this has not already been done
if not (hasattr(sys.excepthook, 'implements') and sys.excepthook.implements('ExceptionHandler')):
original_excepthook = sys.excepthook
sys.excepthook = ExceptionHandler()