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):
40
    e.args = (strings.ensure_newl(strings.ustr(e))+strings.ustr(msg),)
41

    
42
def repl_msg(e, **repls): e.args = (strings.ustr(e) % repls,)
43

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

    
46
class ExceptionWithCause(Exception):
47
    def __init__(self, msg, cause=None, cause_newline=False):
48
        add_traceback(self)
49
        if cause != None:
50
            if cause_newline: msg += '\ncause'
51
            msg += ': '+str_(cause)
52
        Exception.__init__(self, msg)
53

    
54
def str_(e, first_line_only=False):
55
    if isinstance(e, SyntaxError):
56
        # format_exception_only() provides special formatting for SyntaxErrors.
57
        msg = u''.join(traceback.format_exception_only(type(e), e))
58
    else:
59
        # Avoid traceback exception-formatting functions because they escape
60
        # non-ASCII characters with \x, causing exception parsers to read an
61
        # incorrect, escaped value.
62
        msg = util.class_name(e)+': '+e.args[0]
63
    
64
    if first_line_only: msg = msg.partition('\n')[0]
65
    return msg.rstrip()
66

    
67
def print_ex(e, emph=True, detail=True, plain=False):
68
    if plain:
69
        emph = False
70
        detail = False
71
    
72
    msg = str_(e)+'\n'
73
    if detail: msg += get_e_tracebacks_str(e)
74
    if emph:
75
        first_line, nl, rest = msg.partition('\n')
76
        msg = term.error(first_line)+nl+rest
77
    sys.stderr.write(msg)
78

    
79
class ExTracker:
80
    def __init__(self):
81
        self.e_ct = 0
82
    
83
    def msg(self): return 'Encountered '+str(self.e_ct)+' error(s)'
84
    
85
    def track(self, e, **format):
86
        self.e_ct += 1
87
        print_ex(e, **format)
88
    
89
    def exit(self):
90
        if self.e_ct > 0: raise SystemExit(e_ct_exit_status(self.e_ct))
91

    
92
class ExPercentTracker(ExTracker):
93
    def __init__(self, iter_text='iteration'):
94
        ExTracker.__init__(self)
95
        self.iter_text = iter_text
96
        self.iter_ct = None
97
        self.err_iter_ct = None
98
        self.last_iter_num = None
99
    
100
    def add_iters(self, iter_ct):
101
        if self.iter_ct == None: self.iter_ct = 0
102
        self.iter_ct += iter_ct
103
    
104
    def track(self, e, iter_num=None, **format):
105
        if iter_num != None:
106
            if iter_num != self.last_iter_num: # a new iter produced an error
107
                if self.err_iter_ct == None: self.err_iter_ct = 0
108
                self.err_iter_ct += 1
109
                self.last_iter_num = iter_num
110
        ExTracker.track(self, e, **format)
111
    
112
    def msg(self):
113
        msg = ExTracker.msg(self)
114
        iter_text_plural = self.iter_text+'(s)'
115
        numerator = self.e_ct
116
        if self.err_iter_ct != None:
117
            msg += ' in '+format.int2str(self.err_iter_ct)
118
            numerator = self.err_iter_ct
119
        if self.iter_ct != None and self.iter_ct > 0:
120
            msg += ('/'+format.int2str(self.iter_ct)+' '+iter_text_plural+' = '
121
            +format.to_percent(float(numerator)/self.iter_ct))
122
        return msg
(13-13/36)