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 e_msg(e):
40
    assert len(e.args) == 1
41
    assert util.is_str(e.args[0])
42
    return strings.ustr(e.args[0]).rstrip()
43

    
44
def e_str(e): return e.__class__.__name__+': '+e_msg(e)
45

    
46
def add_msg(e, msg):
47
    e.args = (e_msg(e)+'\n'+strings.ustr(msg),)
48

    
49
def repl_msg(e, **repls): e.args = (e_msg(e) % repls,)
50

    
51
def e_ct_exit_status(e_ct): return min(e_ct, 255)
52

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

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

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

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

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