Project

General

Profile

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