Project

General

Profile

1 11 aaronmk
# Exception handling
2
3 6671 aaronmk
import atexit
4 1371 aaronmk
import copy
5 343 aaronmk
import sys
6 1368 aaronmk
import traceback
7 6671 aaronmk
import warnings
8 13 aaronmk
9 989 aaronmk
import format
10 343 aaronmk
import strings
11 826 aaronmk
import term
12 343 aaronmk
import util
13
14 3659 aaronmk
def reraise(e=None): raise
15 3658 aaronmk
16 445 aaronmk
def raise_(e): raise e
17
18 1371 aaronmk
def sys_traceback():
19
    '''Note that Python tracebacks seems to have a bug that truncates them to
20
    only a few stack frames. See <http://bugs.python.org/issue7378>.'''
21
    return sys.exc_info()[2]
22
        # can't just return pointer to traceback because it will change :-(
23 1368 aaronmk
24 1576 aaronmk
def has_tracebacks(e): return hasattr(e, 'tracebacks')
25 1368 aaronmk
26 1371 aaronmk
def add_traceback(e):
27
    '''Adds current traceback to an exception if it doesn't already have one'''
28
    traceback_ = sys_traceback() # get first in case later code throws exception
29 1576 aaronmk
    if not has_tracebacks(e): e.tracebacks = []
30
    if util.list_get(e.tracebacks, 0) == traceback_: return
31
    e.tracebacks.insert(0, traceback_) # tracebacks have most recent call last
32 1371 aaronmk
33 1576 aaronmk
def get_traceback_str(traceback_):
34 1371 aaronmk
    return ''.join(traceback.format_exception(None, None, traceback_)[:-1])
35
        # remove final "None" line ("exception name")
36
37 1576 aaronmk
def get_e_tracebacks_str(e):
38 3656 aaronmk
    traceback_ = sys_traceback() # get first in case later code throws exception
39 1576 aaronmk
    try: tracebacks = e.tracebacks
40 3656 aaronmk
    except AttributeError: tracebacks = [traceback_]
41 1576 aaronmk
    return ''.join(get_traceback_str(t) for t in tracebacks)
42
43 3606 aaronmk
def e_msg(e):
44 4491 aaronmk
    if len(e.args) == 0: return strings.ustr(e)
45 6671 aaronmk
    arg0 = e.args[0]
46
    if not util.is_str(arg0):
47
        warnings.warn(UserWarning('e.args[0] should be a string: '+repr(arg0)))
48
    return strings.ustr(arg0).rstrip()
49 3602 aaronmk
50
def e_str(e): return e.__class__.__name__+': '+e_msg(e)
51
52 2342 aaronmk
def add_msg(e, msg):
53 4112 aaronmk
    e.args = (strings.to_raw_str(e_msg(e)+'\n'+strings.ustr(msg)),)
54 343 aaronmk
55 3604 aaronmk
def repl_msg(e, **repls): e.args = (e_msg(e) % repls,)
56 279 aaronmk
57 974 aaronmk
def e_ct_exit_status(e_ct): return min(e_ct, 255)
58
59 13 aaronmk
class ExceptionWithCause(Exception):
60 2144 aaronmk
    def __init__(self, msg, cause=None, cause_newline=False):
61 1610 aaronmk
        add_traceback(self)
62 2756 aaronmk
63 2144 aaronmk
        if cause != None:
64
            if cause_newline: msg += '\ncause'
65
            msg += ': '+str_(cause)
66 2756 aaronmk
67 13 aaronmk
        Exception.__init__(self, msg)
68 2756 aaronmk
69
        self.cause = cause
70 343 aaronmk
71 2308 aaronmk
def str_(e, first_line_only=False):
72 2372 aaronmk
    if isinstance(e, SyntaxError):
73
        # format_exception_only() provides special formatting for SyntaxErrors.
74 3605 aaronmk
        msg = (u''.join(traceback.format_exception_only(type(e), e))).rstrip()
75 2372 aaronmk
    else:
76
        # Avoid traceback exception-formatting functions because they escape
77
        # non-ASCII characters with \x, causing exception parsers to read an
78
        # incorrect, escaped value.
79 3605 aaronmk
        msg = e_str(e)
80 2372 aaronmk
81 2308 aaronmk
    if first_line_only: msg = msg.partition('\n')[0]
82 3605 aaronmk
    return msg
83 433 aaronmk
84 2045 aaronmk
def print_ex(e, emph=True, detail=True, plain=False):
85
    if plain:
86
        emph = False
87
        detail = False
88 1938 aaronmk
89
    msg = str_(e)+'\n'
90 2045 aaronmk
    if detail: msg += get_e_tracebacks_str(e)
91 826 aaronmk
    if emph:
92
        first_line, nl, rest = msg.partition('\n')
93
        msg = term.error(first_line)+nl+rest
94 2883 aaronmk
    sys.stderr.write(strings.to_raw_str(msg))
95 788 aaronmk
96 433 aaronmk
class ExTracker:
97
    def __init__(self):
98
        self.e_ct = 0
99
100 974 aaronmk
    def msg(self): return 'Encountered '+str(self.e_ct)+' error(s)'
101
102 433 aaronmk
    def track(self, e, **format):
103
        self.e_ct += 1
104
        print_ex(e, **format)
105 985 aaronmk
106
    def exit(self):
107
        if self.e_ct > 0: raise SystemExit(e_ct_exit_status(self.e_ct))
108 975 aaronmk
109
class ExPercentTracker(ExTracker):
110 983 aaronmk
    def __init__(self, iter_text='iteration'):
111 977 aaronmk
        ExTracker.__init__(self)
112 983 aaronmk
        self.iter_text = iter_text
113 977 aaronmk
        self.iter_ct = None
114 1616 aaronmk
        self.err_iter_ct = None
115
        self.last_iter_num = None
116 975 aaronmk
117 977 aaronmk
    def add_iters(self, iter_ct):
118
        if self.iter_ct == None: self.iter_ct = 0
119
        self.iter_ct += iter_ct
120
121 1616 aaronmk
    def track(self, e, iter_num=None, **format):
122
        if iter_num != None:
123
            if iter_num != self.last_iter_num: # a new iter produced an error
124
                if self.err_iter_ct == None: self.err_iter_ct = 0
125
                self.err_iter_ct += 1
126
                self.last_iter_num = iter_num
127
        ExTracker.track(self, e, **format)
128
129 977 aaronmk
    def msg(self):
130
        msg = ExTracker.msg(self)
131 1616 aaronmk
        iter_text_plural = self.iter_text+'(s)'
132
        numerator = self.e_ct
133
        if self.err_iter_ct != None:
134 1618 aaronmk
            msg += ' in '+format.int2str(self.err_iter_ct)
135 1616 aaronmk
            numerator = self.err_iter_ct
136 1648 aaronmk
        if self.iter_ct != None and self.iter_ct > 0:
137 1616 aaronmk
            msg += ('/'+format.int2str(self.iter_ct)+' '+iter_text_plural+' = '
138
            +format.to_percent(float(numerator)/self.iter_ct))
139 977 aaronmk
        return msg