1 |
11
|
aaronmk
|
# Exception handling
|
2 |
|
|
|
3 |
433
|
aaronmk
|
import atexit
|
4 |
343
|
aaronmk
|
import sys
|
5 |
13
|
aaronmk
|
|
6 |
343
|
aaronmk
|
import strings
|
7 |
826
|
aaronmk
|
import term
|
8 |
343
|
aaronmk
|
import util
|
9 |
|
|
|
10 |
445
|
aaronmk
|
def raise_(e): raise e
|
11 |
|
|
|
12 |
343
|
aaronmk
|
def add_msg(e, msg): e.args = (strings.ensure_newl(str(e))+msg,)
|
13 |
|
|
|
14 |
286
|
aaronmk
|
def repl_msg(e, **repls): e.args = (str(e) % repls,)
|
15 |
279
|
aaronmk
|
|
16 |
974
|
aaronmk
|
def e_ct_exit_status(e_ct): return min(e_ct, 255)
|
17 |
|
|
|
18 |
13
|
aaronmk
|
class ExceptionWithCause(Exception):
|
19 |
|
|
def __init__(self, msg, cause=None):
|
20 |
|
|
Exception.__init__(self, msg)
|
21 |
788
|
aaronmk
|
if cause != None: add_msg(self, 'cause: '+str_(cause))
|
22 |
343
|
aaronmk
|
|
23 |
788
|
aaronmk
|
def str_(e, with_name=True):
|
24 |
343
|
aaronmk
|
msg = strings.ensure_newl(str(e))
|
25 |
|
|
if with_name: msg = util.type_name(e)+': '+msg
|
26 |
788
|
aaronmk
|
return msg
|
27 |
433
|
aaronmk
|
|
28 |
973
|
aaronmk
|
def print_ex(e, emph=True, **format):
|
29 |
826
|
aaronmk
|
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 |
788
|
aaronmk
|
|
35 |
433
|
aaronmk
|
class ExTracker:
|
36 |
|
|
def __init__(self):
|
37 |
|
|
self.e_ct = 0
|
38 |
|
|
def at_exit():
|
39 |
974
|
aaronmk
|
sys.stderr.write(self.msg()+'\n')
|
40 |
|
|
if self.e_ct > 0: raise SystemExit(e_ct_exit_status(self.e_ct))
|
41 |
433
|
aaronmk
|
atexit.register(at_exit)
|
42 |
|
|
|
43 |
974
|
aaronmk
|
def msg(self): return 'Encountered '+str(self.e_ct)+' error(s)'
|
44 |
|
|
|
45 |
433
|
aaronmk
|
def track(self, e, **format):
|
46 |
|
|
self.e_ct += 1
|
47 |
|
|
print_ex(e, **format)
|
48 |
975
|
aaronmk
|
|
49 |
|
|
class ExPercentTracker(ExTracker):
|
50 |
977
|
aaronmk
|
def __init__(self):
|
51 |
|
|
ExTracker.__init__(self)
|
52 |
|
|
self.iter_ct = None
|
53 |
975
|
aaronmk
|
|
54 |
977
|
aaronmk
|
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 += ('/'+str(self.iter_ct)+' iterations = '
|
61 |
|
|
+util.to_percent(float(self.e_ct)/self.iter_ct))
|
62 |
|
|
return msg
|