Project

General

Profile

1
# Exception handling
2

    
3
import copy
4
import atexit
5
import sys
6
import traceback
7

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

    
13
def raise_(e): raise e
14

    
15
def sys_traceback():
16
    '''Note that Python tracebacks seems to have a bug that truncates them to
17
    only a few stack frames. See <http://bugs.python.org/issue7378>.'''
18
    return sys.exc_info()[2]
19
        # can't just return pointer to traceback because it will change :-(
20

    
21
def has_tracebacks(e): return hasattr(e, 'tracebacks')
22

    
23
def add_traceback(e):
24
    '''Adds current traceback to an exception if it doesn't already have one'''
25
    traceback_ = sys_traceback() # get first in case later code throws exception
26
    if not has_tracebacks(e): e.tracebacks = []
27
    if util.list_get(e.tracebacks, 0) == traceback_: return
28
    e.tracebacks.insert(0, traceback_) # tracebacks have most recent call last
29

    
30
def get_traceback_str(traceback_):
31
    return ''.join(traceback.format_exception(None, None, traceback_)[:-1])
32
        # remove final "None" line ("exception name")
33

    
34
def get_e_tracebacks_str(e):
35
    try: tracebacks = e.tracebacks
36
    except AttributeError: return ''
37
    return ''.join(get_traceback_str(t) for t in tracebacks)
38

    
39
def add_msg(e, msg): e.args = (strings.ensure_newl(str(e))+msg,)
40

    
41
def repl_msg(e, **repls): e.args = (str(e) % repls,)
42

    
43
def e_ct_exit_status(e_ct): return min(e_ct, 255)
44

    
45
class ExceptionWithCause(Exception):
46
    def __init__(self, msg, cause=None):
47
        Exception.__init__(self, msg)
48
        add_traceback(self)
49
        if cause != None: add_msg(self, 'cause: '+str_(cause))
50

    
51
def str_(e): return ''.join(traceback.format_exception_only(type(e), e))
52

    
53
def print_ex(e, emph=True):
54
    msg = strings.ensure_newl(str_(e))+get_e_tracebacks_str(e)
55
    if emph:
56
        first_line, nl, rest = msg.partition('\n')
57
        msg = term.error(first_line)+nl+rest
58
    sys.stderr.write(msg)
59

    
60
class ExTracker:
61
    def __init__(self):
62
        self.e_ct = 0
63
    
64
    def msg(self): return 'Encountered '+str(self.e_ct)+' error(s)'
65
    
66
    def track(self, e, **format):
67
        self.e_ct += 1
68
        print_ex(e, **format)
69
    
70
    def exit(self):
71
        if self.e_ct > 0: raise SystemExit(e_ct_exit_status(self.e_ct))
72

    
73
class ExPercentTracker(ExTracker):
74
    def __init__(self, iter_text='iteration'):
75
        ExTracker.__init__(self)
76
        self.iter_text = iter_text
77
        self.iter_ct = None
78
    
79
    def add_iters(self, iter_ct):
80
        if self.iter_ct == None: self.iter_ct = 0
81
        self.iter_ct += iter_ct
82
    
83
    def msg(self):
84
        msg = ExTracker.msg(self)
85
        if self.iter_ct != None: msg += ('/'+format.int2str(self.iter_ct)+' '
86
            +self.iter_text+'(s) = '
87
            +format.to_percent(float(self.e_ct)/self.iter_ct))
88
        return msg
(7-7/20)