1
|
# Exception handling
|
2
|
|
3
|
import atexit
|
4
|
import sys
|
5
|
|
6
|
import strings
|
7
|
import term
|
8
|
import util
|
9
|
|
10
|
def raise_(e): raise e
|
11
|
|
12
|
def add_msg(e, msg): e.args = (strings.ensure_newl(str(e))+msg,)
|
13
|
|
14
|
def repl_msg(e, **repls): e.args = (str(e) % repls,)
|
15
|
|
16
|
def e_ct_exit_status(e_ct): return min(e_ct, 255)
|
17
|
|
18
|
class ExceptionWithCause(Exception):
|
19
|
def __init__(self, msg, cause=None):
|
20
|
Exception.__init__(self, msg)
|
21
|
if cause != None: add_msg(self, 'cause: '+str_(cause))
|
22
|
|
23
|
def str_(e, with_name=True):
|
24
|
msg = strings.ensure_newl(str(e))
|
25
|
if with_name: msg = util.type_name(e)+': '+msg
|
26
|
return msg
|
27
|
|
28
|
def print_ex(e, emph=True, **format):
|
29
|
msg = str_(e, **format)
|
30
|
if emph:
|
31
|
first_line, nl, rest = msg.partition('\n')
|
32
|
msg = term.error(first_line)+nl+rest
|
33
|
sys.stderr.write(msg)
|
34
|
|
35
|
class ExTracker:
|
36
|
def __init__(self):
|
37
|
self.e_ct = 0
|
38
|
|
39
|
def msg(self): return 'Encountered '+str(self.e_ct)+' error(s)'
|
40
|
|
41
|
def track(self, e, **format):
|
42
|
self.e_ct += 1
|
43
|
print_ex(e, **format)
|
44
|
|
45
|
def exit(self):
|
46
|
if self.e_ct > 0: raise SystemExit(e_ct_exit_status(self.e_ct))
|
47
|
|
48
|
class ExPercentTracker(ExTracker):
|
49
|
def __init__(self, iter_text='iteration'):
|
50
|
ExTracker.__init__(self)
|
51
|
self.iter_text = iter_text
|
52
|
self.iter_ct = None
|
53
|
|
54
|
def add_iters(self, iter_ct):
|
55
|
if self.iter_ct == None: self.iter_ct = 0
|
56
|
self.iter_ct += iter_ct
|
57
|
|
58
|
def msg(self):
|
59
|
msg = ExTracker.msg(self)
|
60
|
if self.iter_ct != None: msg += ('/'+util.int2str(self.iter_ct)+' '
|
61
|
+self.iter_text+'(s) = '
|
62
|
+util.to_percent(float(self.e_ct)/self.iter_ct))
|
63
|
return msg
|