Project

General

Profile

1
# Exception handling
2

    
3
import atexit
4
import sys
5
import traceback
6

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

    
12
def raise_(e): raise e
13

    
14
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
def add_msg(e, msg): e.args = (strings.ensure_newl(str(e))+msg,)
26

    
27
def repl_msg(e, **repls): e.args = (str(e) % repls,)
28

    
29
def e_ct_exit_status(e_ct): return min(e_ct, 255)
30

    
31
class ExceptionWithCause(Exception):
32
    def __init__(self, msg, cause=None):
33
        Exception.__init__(self, msg)
34
        if cause != None: add_msg(self, 'cause: '+str_(cause))
35

    
36
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

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

    
48
class ExTracker:
49
    def __init__(self):
50
        self.e_ct = 0
51
    
52
    def msg(self): return 'Encountered '+str(self.e_ct)+' error(s)'
53
    
54
    def track(self, e, **format):
55
        self.e_ct += 1
56
        print_ex(e, **format)
57
    
58
    def exit(self):
59
        if self.e_ct > 0: raise SystemExit(e_ct_exit_status(self.e_ct))
60

    
61
class ExPercentTracker(ExTracker):
62
    def __init__(self, iter_text='iteration'):
63
        ExTracker.__init__(self)
64
        self.iter_text = iter_text
65
        self.iter_ct = None
66
    
67
    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
        if self.iter_ct != None: msg += ('/'+format.int2str(self.iter_ct)+' '
74
            +self.iter_text+'(s) = '
75
            +format.to_percent(float(self.e_ct)/self.iter_ct))
76
        return msg
(5-5/17)