Project

General

Profile

1
# Exception handling
2

    
3
import atexit
4
import sys
5

    
6
import format
7
import strings
8
import term
9
import util
10

    
11
def raise_(e): raise e
12

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

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

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

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

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

    
29
def print_ex(e, emph=True, **format):
30
    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

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

    
49
class ExPercentTracker(ExTracker):
50
    def __init__(self, iter_text='iteration'):
51
        ExTracker.__init__(self)
52
        self.iter_text = iter_text
53
        self.iter_ct = None
54
    
55
    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
        if self.iter_ct != None: msg += ('/'+format.int2str(self.iter_ct)+' '
62
            +self.iter_text+'(s) = '
63
            +format.to_percent(float(self.e_ct)/self.iter_ct))
64
        return msg
(5-5/17)