2 from __future__ import absolute_import, print_function
3 from array import array
4 from traceback import print_exception
7 # Please see CODINGSTYLE for important exception handling guidelines
8 # and the rationale behind add_ex_tb(), add_ex_ctx(), etc.
10 py_maj = sys.version_info[0]
15 from shlex import quote
20 """Do nothing (already handled by Python 3 infrastructure)."""
23 def add_ex_ctx(ex, context_ex):
24 """Do nothing (already handled by Python 3 infrastructure)."""
30 def bytes_from_uint(i):
33 byte_int = lambda x: x
35 def buffer(object, offset=None, size=None):
37 assert offset is not None
38 return memoryview(object)[offset:offset + size]
40 return memoryview(object)[offset:]
41 return memoryview(object)
43 def join_bytes(*items):
44 """Return the concatenated bytes or memoryview arguments as bytes."""
45 return b''.join(*items)
49 from pipes import quote
54 """Add a traceback to ex if it doesn't already have one. Return ex.
57 if not getattr(ex, '__traceback__', None):
58 ex.__traceback__ = sys.exc_info()[2]
61 def add_ex_ctx(ex, context_ex):
62 """Make context_ex the __context__ of ex (unless it already has one).
67 if not getattr(ex, '__context__', None):
68 ex.__context__ = context_ex
71 def dump_traceback(ex):
73 next_ex = getattr(ex, '__context__', None)
76 next_ex = getattr(next_ex, '__context__', None)
77 stack = reversed(stack)
79 tb = getattr(ex, '__traceback__', None)
80 print_exception(type(ex), ex, tb)
82 print('\nDuring handling of the above exception, another exception occurred:\n',
84 tb = getattr(ex, '__traceback__', None)
85 print_exception(type(ex), ex, tb)
90 def bytes_from_uint(i):
98 """Return the concatenated bytes or buffer arguments as bytes."""
100 assert type(y) in (bytes, buffer)
102 assert type(x) == bytes
104 return b''.join((x, y))
105 assert type(y) in (bytes, buffer)
109 """Run main() and raise a SystemExit with the return value if it
110 returns, pass along any SystemExit it raises, convert
111 KeyboardInterrupts into exit(130), and print a Python 3 style
112 contextual backtrace for other exceptions in both Python 2 and
116 except KeyboardInterrupt as ex:
118 except SystemExit as ex:
120 except BaseException as ex:
128 # Excepting wrap_main() in the traceback, these should produce similar output:
129 # python2 lib/bup/compat.py
130 # python3 lib/bup/compat.py
132 # diff -u <(python2 lib/bup/compat.py 2>&1) <(python3 lib/bup/compat.py 2>&1)
134 # Though the python3 output for 'second' will include a stacktrace
135 # starting from wrap_main, rather than from outer().
137 if __name__ == '__main__':
140 raise Exception('first')
145 except Exception as ex:
148 raise Exception('second')
149 except Exception as ex2:
150 raise add_ex_ctx(add_ex_tb(ex2), ex)