Project

General

Profile

1 11 aaronmk
# Exception handling
2
3 433 aaronmk
import atexit
4 343 aaronmk
import sys
5 1368 aaronmk
import traceback
6 13 aaronmk
7 989 aaronmk
import format
8 343 aaronmk
import strings
9 826 aaronmk
import term
10 343 aaronmk
import util
11
12 445 aaronmk
def raise_(e): raise e
13
14 1368 aaronmk
def add_exc_info(e):
15
    '''Note that this will create a circular reference in the traceback
16
    (See <http://docs.python.org/library/sys.html#sys.exc_info>)'''
17
    e.exc_info = sys.exc_info()
18
19
def get_exc_info(e):
20
    try: exc_info = e.exc_info
21
    except AttributeError: exc_info = sys.exc_info()
22
    assert exc_info[1] is e
23
    return exc_info
24
25 343 aaronmk
def add_msg(e, msg): e.args = (strings.ensure_newl(str(e))+msg,)
26
27 286 aaronmk
def repl_msg(e, **repls): e.args = (str(e) % repls,)
28 279 aaronmk
29 974 aaronmk
def e_ct_exit_status(e_ct): return min(e_ct, 255)
30
31 13 aaronmk
class ExceptionWithCause(Exception):
32
    def __init__(self, msg, cause=None):
33
        Exception.__init__(self, msg)
34 788 aaronmk
        if cause != None: add_msg(self, 'cause: '+str_(cause))
35 343 aaronmk
36 1368 aaronmk
def str_(e, with_traceback=True):
37
    lines = traceback.format_exception_only(type(e), e)
38
    if with_traceback: lines += traceback.format_tb(get_exc_info(e)[2])
39
    return ''.join(lines)
40 433 aaronmk
41 973 aaronmk
def print_ex(e, emph=True, **format):
42 826 aaronmk
    msg = str_(e, **format)
43
    if emph:
44
        first_line, nl, rest = msg.partition('\n')
45
        msg = term.error(first_line)+nl+rest
46
    sys.stderr.write(msg)
47 788 aaronmk
48 433 aaronmk
class ExTracker:
49
    def __init__(self):
50
        self.e_ct = 0
51
52 974 aaronmk
    def msg(self): return 'Encountered '+str(self.e_ct)+' error(s)'
53
54 433 aaronmk
    def track(self, e, **format):
55
        self.e_ct += 1
56
        print_ex(e, **format)
57 985 aaronmk
58
    def exit(self):
59
        if self.e_ct > 0: raise SystemExit(e_ct_exit_status(self.e_ct))
60 975 aaronmk
61
class ExPercentTracker(ExTracker):
62 983 aaronmk
    def __init__(self, iter_text='iteration'):
63 977 aaronmk
        ExTracker.__init__(self)
64 983 aaronmk
        self.iter_text = iter_text
65 977 aaronmk
        self.iter_ct = None
66 975 aaronmk
67 977 aaronmk
    def add_iters(self, iter_ct):
68
        if self.iter_ct == None: self.iter_ct = 0
69
        self.iter_ct += iter_ct
70
71
    def msg(self):
72
        msg = ExTracker.msg(self)
73 989 aaronmk
        if self.iter_ct != None: msg += ('/'+format.int2str(self.iter_ct)+' '
74 988 aaronmk
            +self.iter_text+'(s) = '
75 989 aaronmk
            +format.to_percent(float(self.e_ct)/self.iter_ct))
76 977 aaronmk
        return msg