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 reraise(e=None): raise
14

    
15
def raise_(e): raise e
16

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

    
23
def has_tracebacks(e): return hasattr(e, 'tracebacks')
24

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

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

    
36
def get_e_tracebacks_str(e):
37
    traceback_ = sys_traceback() # get first in case later code throws exception
38
    try: tracebacks = e.tracebacks
39
    except AttributeError: tracebacks = [traceback_]
40
    return ''.join(get_traceback_str(t) for t in tracebacks)
41

    
42
def e_msg(e):
43
    if len(e.args) == 0: return strings.ustr(e)
44
    assert util.is_str(e.args[0])
45
    return strings.ustr(e.args[0]).rstrip()
46

    
47
def e_str(e): return e.__class__.__name__+': '+e_msg(e)
48

    
49
def add_msg(e, msg):
50
    e.args = (strings.to_raw_str(e_msg(e)+'\n'+strings.ustr(msg)),)
51

    
52
def repl_msg(e, **repls): e.args = (e_msg(e) % repls,)
53

    
54
def e_ct_exit_status(e_ct): return min(e_ct, 255)
55

    
56
class ExceptionWithCause(Exception):
57
    def __init__(self, msg, cause=None, cause_newline=False):
58
        add_traceback(self)
59
        
60
        if cause != None:
61
            if cause_newline: msg += '\ncause'
62
            msg += ': '+str_(cause)
63
        
64
        Exception.__init__(self, msg)
65
        
66
        self.cause = cause
67

    
68
def str_(e, first_line_only=False):
69
    if isinstance(e, SyntaxError):
70
        # format_exception_only() provides special formatting for SyntaxErrors.
71
        msg = (u''.join(traceback.format_exception_only(type(e), e))).rstrip()
72
    else:
73
        # Avoid traceback exception-formatting functions because they escape
74
        # non-ASCII characters with \x, causing exception parsers to read an
75
        # incorrect, escaped value.
76
        msg = e_str(e)
77
    
78
    if first_line_only: msg = msg.partition('\n')[0]
79
    return msg
80

    
81
def print_ex(e, emph=True, detail=True, plain=False):
82
    if plain:
83
        emph = False
84
        detail = False
85
    
86
    msg = str_(e)+'\n'
87
    if detail: msg += get_e_tracebacks_str(e)
88
    if emph:
89
        first_line, nl, rest = msg.partition('\n')
90
        msg = term.error(first_line)+nl+rest
91
    sys.stderr.write(strings.to_raw_str(msg))
92

    
93
class ExTracker:
94
    def __init__(self):
95
        self.e_ct = 0
96
    
97
    def msg(self): return 'Encountered '+str(self.e_ct)+' error(s)'
98
    
99
    def track(self, e, **format):
100
        self.e_ct += 1
101
        print_ex(e, **format)
102
    
103
    def exit(self):
104
        if self.e_ct > 0: raise SystemExit(e_ct_exit_status(self.e_ct))
105

    
106
class ExPercentTracker(ExTracker):
107
    def __init__(self, iter_text='iteration'):
108
        ExTracker.__init__(self)
109
        self.iter_text = iter_text
110
        self.iter_ct = None
111
        self.err_iter_ct = None
112
        self.last_iter_num = None
113
    
114
    def add_iters(self, iter_ct):
115
        if self.iter_ct == None: self.iter_ct = 0
116
        self.iter_ct += iter_ct
117
    
118
    def track(self, e, iter_num=None, **format):
119
        if iter_num != None:
120
            if iter_num != self.last_iter_num: # a new iter produced an error
121
                if self.err_iter_ct == None: self.err_iter_ct = 0
122
                self.err_iter_ct += 1
123
                self.last_iter_num = iter_num
124
        ExTracker.track(self, e, **format)
125
    
126
    def msg(self):
127
        msg = ExTracker.msg(self)
128
        iter_text_plural = self.iter_text+'(s)'
129
        numerator = self.e_ct
130
        if self.err_iter_ct != None:
131
            msg += ' in '+format.int2str(self.err_iter_ct)
132
            numerator = self.err_iter_ct
133
        if self.iter_ct != None and self.iter_ct > 0:
134
            msg += ('/'+format.int2str(self.iter_ct)+' '+iter_text_plural+' = '
135
            +format.to_percent(float(numerator)/self.iter_ct))
136
        return msg
(14-14/40)