Project

General

Profile

1
# Exception handling
2

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

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

    
14
def reraise(e=None): raise
15

    
16
def raise_(e): raise e
17

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

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

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

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

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

    
43
def e_msg(e):
44
    if len(e.args) == 0: return strings.ustr(e)
45
    arg0 = e.args[0]
46
    if not util.is_str(arg0):
47
        warnings.warn(UserWarning('e.args[0] should be a string: '+repr(arg0)))
48
    return strings.ustr(arg0).rstrip()
49

    
50
def e_str(e): return e.__class__.__name__+': '+e_msg(e)
51

    
52
def add_msg(e, msg):
53
    e.args = (strings.to_raw_str(e_msg(e)+'\n'+strings.ustr(msg)),)
54

    
55
def repl_msg(e, **repls): e.args = (e_msg(e) % repls,)
56

    
57
def e_ct_exit_status(e_ct): return min(e_ct, 255)
58

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

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

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

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

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