Project

General

Profile

1
# Exception handling
2

    
3
import atexit
4
import sys
5

    
6
import strings
7
import term
8
import util
9

    
10
def raise_(e): raise e
11

    
12
def add_msg(e, msg): e.args = (strings.ensure_newl(str(e))+msg,)
13

    
14
def repl_msg(e, **repls): e.args = (str(e) % repls,)
15

    
16
def e_ct_exit_status(e_ct): return min(e_ct, 255)
17

    
18
class ExceptionWithCause(Exception):
19
    def __init__(self, msg, cause=None):
20
        Exception.__init__(self, msg)
21
        if cause != None: add_msg(self, 'cause: '+str_(cause))
22

    
23
def str_(e, with_name=True):
24
    msg = strings.ensure_newl(str(e))
25
    if with_name: msg = util.type_name(e)+': '+msg
26
    return msg
27

    
28
def print_ex(e, emph=True, **format):
29
    msg = str_(e, **format)
30
    if emph:
31
        first_line, nl, rest = msg.partition('\n')
32
        msg = term.error(first_line)+nl+rest
33
    sys.stderr.write(msg)
34

    
35
class ExTracker:
36
    def __init__(self):
37
        self.e_ct = 0
38
        def at_exit():
39
            sys.stderr.write(self.msg()+'\n')
40
            if self.e_ct > 0: raise SystemExit(e_ct_exit_status(self.e_ct))
41
        atexit.register(at_exit)
42
    
43
    def msg(self): return 'Encountered '+str(self.e_ct)+' error(s)'
44
    
45
    def track(self, e, **format):
46
        self.e_ct += 1
47
        print_ex(e, **format)
48

    
49
class ExPercentTracker(ExTracker):
50
    def __init__(self):
51
        ExTracker.__init__(self)
52
        self.iter_ct = None
53
    
54
    def add_iters(self, iter_ct):
55
        if self.iter_ct == None: self.iter_ct = 0
56
        self.iter_ct += iter_ct
57
    
58
    def msg(self):
59
        msg = ExTracker.msg(self)
60
        if self.iter_ct != None: msg += ('/'+str(self.iter_ct)+' iterations = '
61
            +util.to_percent(float(self.e_ct)/self.iter_ct))
62
        return msg
(5-5/14)