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
    try: tracebacks = e.tracebacks
36
    except AttributeError: return ''
37
    return ''.join(get_traceback_str(t) for t in tracebacks)
38
39 2342 aaronmk
def add_msg(e, msg):
40
    e.args = (strings.ensure_newl(strings.ustr(e))+strings.ustr(msg),)
41 343 aaronmk
42 2246 aaronmk
def repl_msg(e, **repls): e.args = (strings.ustr(e) % repls,)
43 279 aaronmk
44 974 aaronmk
def e_ct_exit_status(e_ct): return min(e_ct, 255)
45
46 13 aaronmk
class ExceptionWithCause(Exception):
47 2144 aaronmk
    def __init__(self, msg, cause=None, cause_newline=False):
48 1610 aaronmk
        add_traceback(self)
49 2756 aaronmk
50 2144 aaronmk
        if cause != None:
51
            if cause_newline: msg += '\ncause'
52
            msg += ': '+str_(cause)
53 2756 aaronmk
54 13 aaronmk
        Exception.__init__(self, msg)
55 2756 aaronmk
56
        self.cause = cause
57 343 aaronmk
58 2308 aaronmk
def str_(e, first_line_only=False):
59 2372 aaronmk
    if isinstance(e, SyntaxError):
60
        # format_exception_only() provides special formatting for SyntaxErrors.
61
        msg = u''.join(traceback.format_exception_only(type(e), e))
62
    else:
63
        # Avoid traceback exception-formatting functions because they escape
64
        # non-ASCII characters with \x, causing exception parsers to read an
65
        # incorrect, escaped value.
66
        msg = util.class_name(e)+': '+e.args[0]
67
68 2308 aaronmk
    if first_line_only: msg = msg.partition('\n')[0]
69 2372 aaronmk
    return msg.rstrip()
70 433 aaronmk
71 2045 aaronmk
def print_ex(e, emph=True, detail=True, plain=False):
72
    if plain:
73
        emph = False
74
        detail = False
75 1938 aaronmk
76
    msg = str_(e)+'\n'
77 2045 aaronmk
    if detail: msg += get_e_tracebacks_str(e)
78 826 aaronmk
    if emph:
79
        first_line, nl, rest = msg.partition('\n')
80
        msg = term.error(first_line)+nl+rest
81
    sys.stderr.write(msg)
82 788 aaronmk
83 433 aaronmk
class ExTracker:
84
    def __init__(self):
85
        self.e_ct = 0
86
87 974 aaronmk
    def msg(self): return 'Encountered '+str(self.e_ct)+' error(s)'
88
89 433 aaronmk
    def track(self, e, **format):
90
        self.e_ct += 1
91
        print_ex(e, **format)
92 985 aaronmk
93
    def exit(self):
94
        if self.e_ct > 0: raise SystemExit(e_ct_exit_status(self.e_ct))
95 975 aaronmk
96
class ExPercentTracker(ExTracker):
97 983 aaronmk
    def __init__(self, iter_text='iteration'):
98 977 aaronmk
        ExTracker.__init__(self)
99 983 aaronmk
        self.iter_text = iter_text
100 977 aaronmk
        self.iter_ct = None
101 1616 aaronmk
        self.err_iter_ct = None
102
        self.last_iter_num = None
103 975 aaronmk
104 977 aaronmk
    def add_iters(self, iter_ct):
105
        if self.iter_ct == None: self.iter_ct = 0
106
        self.iter_ct += iter_ct
107
108 1616 aaronmk
    def track(self, e, iter_num=None, **format):
109
        if iter_num != None:
110
            if iter_num != self.last_iter_num: # a new iter produced an error
111
                if self.err_iter_ct == None: self.err_iter_ct = 0
112
                self.err_iter_ct += 1
113
                self.last_iter_num = iter_num
114
        ExTracker.track(self, e, **format)
115
116 977 aaronmk
    def msg(self):
117
        msg = ExTracker.msg(self)
118 1616 aaronmk
        iter_text_plural = self.iter_text+'(s)'
119
        numerator = self.e_ct
120
        if self.err_iter_ct != None:
121 1618 aaronmk
            msg += ' in '+format.int2str(self.err_iter_ct)
122 1616 aaronmk
            numerator = self.err_iter_ct
123 1648 aaronmk
        if self.iter_ct != None and self.iter_ct > 0:
124 1616 aaronmk
            msg += ('/'+format.int2str(self.iter_ct)+' '+iter_text_plural+' = '
125
            +format.to_percent(float(numerator)/self.iter_ct))
126 977 aaronmk
        return msg