2 from __future__ import absolute_import, print_function
3 from traceback import print_exception
6 # Please see CODINGSTYLE for important exception handling guidelines
7 # and the rationale behind add_ex_tb(), add_ex_ctx(), etc.
9 py_maj = sys.version_info[0]
14 from shlex import quote
19 """Do nothing (already handled by Python 3 infrastructure)."""
22 def add_ex_ctx(ex, context_ex):
23 """Do nothing (already handled by Python 3 infrastructure)."""
29 def bytes_from_uint(i):
34 from pipes import quote
39 """Add a traceback to ex if it doesn't already have one. Return ex.
42 if not getattr(ex, '__traceback__', None):
43 ex.__traceback__ = sys.exc_info()[2]
46 def add_ex_ctx(ex, context_ex):
47 """Make context_ex the __context__ of ex (unless it already has one).
52 if not getattr(ex, '__context__', None):
53 ex.__context__ = context_ex
56 def dump_traceback(ex):
58 next_ex = getattr(ex, '__context__', None)
61 next_ex = getattr(next_ex, '__context__', None)
62 stack = reversed(stack)
64 tb = getattr(ex, '__traceback__', None)
65 print_exception(type(ex), ex, tb)
67 print('\nDuring handling of the above exception, another exception occurred:\n',
69 tb = getattr(ex, '__traceback__', None)
70 print_exception(type(ex), ex, tb)
75 def bytes_from_uint(i):
80 """Run main() and raise a SystemExit with the return value if it
81 returns, pass along any SystemExit it raises, convert
82 KeyboardInterrupts into exit(130), and print a Python 3 style
83 contextual backtrace for other exceptions in both Python 2 and
87 except KeyboardInterrupt as ex:
89 except SystemExit as ex:
91 except BaseException as ex:
99 # Excepting wrap_main() in the traceback, these should produce similar output:
100 # python2 lib/bup/compat.py
101 # python3 lib/bup/compat.py
103 # diff -u <(python2 lib/bup/compat.py 2>&1) <(python3 lib/bup/compat.py 2>&1)
105 # Though the python3 output for 'second' will include a stacktrace
106 # starting from wrap_main, rather than from outer().
108 if __name__ == '__main__':
111 raise Exception('first')
116 except Exception as ex:
119 raise Exception('second')
120 except Exception as ex2:
121 raise add_ex_ctx(add_ex_tb(ex2), ex)