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