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 buffer_concat(b1, b2):
44 if isinstance(b1, memoryview):
46 if isinstance(b1, memoryview):
52 from pipes import quote
57 """Add a traceback to ex if it doesn't already have one. Return ex.
60 if not getattr(ex, '__traceback__', None):
61 ex.__traceback__ = sys.exc_info()[2]
64 def add_ex_ctx(ex, context_ex):
65 """Make context_ex the __context__ of ex (unless it already has one).
70 if not getattr(ex, '__context__', None):
71 ex.__context__ = context_ex
74 def dump_traceback(ex):
76 next_ex = getattr(ex, '__context__', None)
79 next_ex = getattr(next_ex, '__context__', None)
80 stack = reversed(stack)
82 tb = getattr(ex, '__traceback__', None)
83 print_exception(type(ex), ex, tb)
85 print('\nDuring handling of the above exception, another exception occurred:\n',
87 tb = getattr(ex, '__traceback__', None)
88 print_exception(type(ex), ex, tb)
93 def bytes_from_uint(i):
98 def buffer_concat(b1, b2):
103 """Run main() and raise a SystemExit with the return value if it
104 returns, pass along any SystemExit it raises, convert
105 KeyboardInterrupts into exit(130), and print a Python 3 style
106 contextual backtrace for other exceptions in both Python 2 and
110 except KeyboardInterrupt as ex:
112 except SystemExit as ex:
114 except BaseException as ex:
122 # Excepting wrap_main() in the traceback, these should produce similar output:
123 # python2 lib/bup/compat.py
124 # python3 lib/bup/compat.py
126 # diff -u <(python2 lib/bup/compat.py 2>&1) <(python3 lib/bup/compat.py 2>&1)
128 # Though the python3 output for 'second' will include a stacktrace
129 # starting from wrap_main, rather than from outer().
131 if __name__ == '__main__':
134 raise Exception('first')
139 except Exception as ex:
142 raise Exception('second')
143 except Exception as ex2:
144 raise add_ex_ctx(add_ex_tb(ex2), ex)