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 1371 aaronmk
def has_traceback(e): return hasattr(e, 'traceback_')
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
    if not has_traceback(e): e.traceback_ = traceback_
27
28
def get_traceback_str(e):
29
    try: traceback_ = e.traceback_
30
    except AttributeError: return ''
31
    return ''.join(traceback.format_exception(None, None, traceback_)[:-1])
32
        # remove final "None" line ("exception name")
33
34 343 aaronmk
def add_msg(e, msg): e.args = (strings.ensure_newl(str(e))+msg,)
35
36 286 aaronmk
def repl_msg(e, **repls): e.args = (str(e) % repls,)
37 279 aaronmk
38 974 aaronmk
def e_ct_exit_status(e_ct): return min(e_ct, 255)
39
40 13 aaronmk
class ExceptionWithCause(Exception):
41
    def __init__(self, msg, cause=None):
42
        Exception.__init__(self, msg)
43 1371 aaronmk
        add_traceback(self)
44 788 aaronmk
        if cause != None: add_msg(self, 'cause: '+str_(cause))
45 343 aaronmk
46 1371 aaronmk
def str_(e): return ''.join(traceback.format_exception_only(type(e), e))
47 433 aaronmk
48 1371 aaronmk
def print_ex(e, emph=True):
49
    msg = strings.ensure_newl(str_(e))+get_traceback_str(e)
50 826 aaronmk
    if emph:
51
        first_line, nl, rest = msg.partition('\n')
52
        msg = term.error(first_line)+nl+rest
53
    sys.stderr.write(msg)
54 788 aaronmk
55 433 aaronmk
class ExTracker:
56
    def __init__(self):
57
        self.e_ct = 0
58
59 974 aaronmk
    def msg(self): return 'Encountered '+str(self.e_ct)+' error(s)'
60
61 433 aaronmk
    def track(self, e, **format):
62
        self.e_ct += 1
63
        print_ex(e, **format)
64 985 aaronmk
65
    def exit(self):
66
        if self.e_ct > 0: raise SystemExit(e_ct_exit_status(self.e_ct))
67 975 aaronmk
68
class ExPercentTracker(ExTracker):
69 983 aaronmk
    def __init__(self, iter_text='iteration'):
70 977 aaronmk
        ExTracker.__init__(self)
71 983 aaronmk
        self.iter_text = iter_text
72 977 aaronmk
        self.iter_ct = None
73 975 aaronmk
74 977 aaronmk
    def add_iters(self, iter_ct):
75
        if self.iter_ct == None: self.iter_ct = 0
76
        self.iter_ct += iter_ct
77
78
    def msg(self):
79
        msg = ExTracker.msg(self)
80 989 aaronmk
        if self.iter_ct != None: msg += ('/'+format.int2str(self.iter_ct)+' '
81 988 aaronmk
            +self.iter_text+'(s) = '
82 989 aaronmk
            +format.to_percent(float(self.e_ct)/self.iter_ct))
83 977 aaronmk
        return msg