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 343 aaronmk
def add_msg(e, msg): e.args = (strings.ensure_newl(str(e))+msg,)
40
41 286 aaronmk
def repl_msg(e, **repls): e.args = (str(e) % repls,)
42 279 aaronmk
43 974 aaronmk
def e_ct_exit_status(e_ct): return min(e_ct, 255)
44
45 13 aaronmk
class ExceptionWithCause(Exception):
46
    def __init__(self, msg, cause=None):
47 1610 aaronmk
        add_traceback(self)
48
        if cause != None: msg += ': '+str_(cause)
49 13 aaronmk
        Exception.__init__(self, msg)
50 343 aaronmk
51 1636 aaronmk
def str_(e):
52
    return ''.join(traceback.format_exception_only(type(e), e)).rstrip()
53 433 aaronmk
54 1938 aaronmk
def print_ex(e, emph=True, plain=False):
55
    if plain: emph = False
56
57
    msg = str_(e)+'\n'
58
    if not plain: msg += get_e_tracebacks_str(e)
59 826 aaronmk
    if emph:
60
        first_line, nl, rest = msg.partition('\n')
61
        msg = term.error(first_line)+nl+rest
62
    sys.stderr.write(msg)
63 788 aaronmk
64 433 aaronmk
class ExTracker:
65
    def __init__(self):
66
        self.e_ct = 0
67
68 974 aaronmk
    def msg(self): return 'Encountered '+str(self.e_ct)+' error(s)'
69
70 433 aaronmk
    def track(self, e, **format):
71
        self.e_ct += 1
72
        print_ex(e, **format)
73 985 aaronmk
74
    def exit(self):
75
        if self.e_ct > 0: raise SystemExit(e_ct_exit_status(self.e_ct))
76 975 aaronmk
77
class ExPercentTracker(ExTracker):
78 983 aaronmk
    def __init__(self, iter_text='iteration'):
79 977 aaronmk
        ExTracker.__init__(self)
80 983 aaronmk
        self.iter_text = iter_text
81 977 aaronmk
        self.iter_ct = None
82 1616 aaronmk
        self.err_iter_ct = None
83
        self.last_iter_num = None
84 975 aaronmk
85 977 aaronmk
    def add_iters(self, iter_ct):
86
        if self.iter_ct == None: self.iter_ct = 0
87
        self.iter_ct += iter_ct
88
89 1616 aaronmk
    def track(self, e, iter_num=None, **format):
90
        if iter_num != None:
91
            if iter_num != self.last_iter_num: # a new iter produced an error
92
                if self.err_iter_ct == None: self.err_iter_ct = 0
93
                self.err_iter_ct += 1
94
                self.last_iter_num = iter_num
95
        ExTracker.track(self, e, **format)
96
97 977 aaronmk
    def msg(self):
98
        msg = ExTracker.msg(self)
99 1616 aaronmk
        iter_text_plural = self.iter_text+'(s)'
100
        numerator = self.e_ct
101
        if self.err_iter_ct != None:
102 1618 aaronmk
            msg += ' in '+format.int2str(self.err_iter_ct)
103 1616 aaronmk
            numerator = self.err_iter_ct
104 1648 aaronmk
        if self.iter_ct != None and self.iter_ct > 0:
105 1616 aaronmk
            msg += ('/'+format.int2str(self.iter_ct)+' '+iter_text_plural+' = '
106
            +format.to_percent(float(numerator)/self.iter_ct))
107 977 aaronmk
        return msg