Project

General

Profile

1 11 aaronmk
# Exception handling
2
3 433 aaronmk
import atexit
4 343 aaronmk
import sys
5 13 aaronmk
6 989 aaronmk
import format
7 343 aaronmk
import strings
8 826 aaronmk
import term
9 343 aaronmk
import util
10
11 445 aaronmk
def raise_(e): raise e
12
13 343 aaronmk
def add_msg(e, msg): e.args = (strings.ensure_newl(str(e))+msg,)
14
15 286 aaronmk
def repl_msg(e, **repls): e.args = (str(e) % repls,)
16 279 aaronmk
17 974 aaronmk
def e_ct_exit_status(e_ct): return min(e_ct, 255)
18
19 13 aaronmk
class ExceptionWithCause(Exception):
20
    def __init__(self, msg, cause=None):
21
        Exception.__init__(self, msg)
22 788 aaronmk
        if cause != None: add_msg(self, 'cause: '+str_(cause))
23 343 aaronmk
24 788 aaronmk
def str_(e, with_name=True):
25 343 aaronmk
    msg = strings.ensure_newl(str(e))
26
    if with_name: msg = util.type_name(e)+': '+msg
27 788 aaronmk
    return msg
28 433 aaronmk
29 973 aaronmk
def print_ex(e, emph=True, **format):
30 826 aaronmk
    msg = str_(e, **format)
31
    if emph:
32
        first_line, nl, rest = msg.partition('\n')
33
        msg = term.error(first_line)+nl+rest
34
    sys.stderr.write(msg)
35 788 aaronmk
36 433 aaronmk
class ExTracker:
37
    def __init__(self):
38
        self.e_ct = 0
39
40 974 aaronmk
    def msg(self): return 'Encountered '+str(self.e_ct)+' error(s)'
41
42 433 aaronmk
    def track(self, e, **format):
43
        self.e_ct += 1
44
        print_ex(e, **format)
45 985 aaronmk
46
    def exit(self):
47
        if self.e_ct > 0: raise SystemExit(e_ct_exit_status(self.e_ct))
48 975 aaronmk
49
class ExPercentTracker(ExTracker):
50 983 aaronmk
    def __init__(self, iter_text='iteration'):
51 977 aaronmk
        ExTracker.__init__(self)
52 983 aaronmk
        self.iter_text = iter_text
53 977 aaronmk
        self.iter_ct = None
54 975 aaronmk
55 977 aaronmk
    def add_iters(self, iter_ct):
56
        if self.iter_ct == None: self.iter_ct = 0
57
        self.iter_ct += iter_ct
58
59
    def msg(self):
60
        msg = ExTracker.msg(self)
61 989 aaronmk
        if self.iter_ct != None: msg += ('/'+format.int2str(self.iter_ct)+' '
62 988 aaronmk
            +self.iter_text+'(s) = '
63 989 aaronmk
            +format.to_percent(float(self.e_ct)/self.iter_ct))
64 977 aaronmk
        return msg