2 from __future__ import print_function
3 from traceback import print_exception
6 py_maj = sys.version_info[0]
14 """Do nothing (already handled by Python 3 infrastructure)."""
17 def chain_ex(ex, context_ex):
18 """Do nothing (already handled by Python 3 infrastructure)."""
26 """Add a traceback to ex if it doesn't already have one. Return ex.
29 if not getattr(ex, '__traceback__', None):
30 ex.__traceback__ = sys.exc_info()[2]
33 def chain_ex(ex, context_ex):
34 """Chain context_ex to ex as the __context__ (unless it already has
39 if not getattr(ex, '__context__', None):
40 ex.__context__ = context_ex
43 def dump_traceback(ex):
45 next_ex = getattr(ex, '__context__', None)
48 next_ex = getattr(next_ex, '__context__', None)
49 stack = reversed(stack)
51 tb = getattr(ex, '__traceback__', None)
52 print_exception(type(ex), ex, tb)
54 print('\nDuring handling of the above exception, another exception occurred:\n',
56 tb = getattr(ex, '__traceback__', None)
57 print_exception(type(ex), ex, tb)
60 """Run main() and raise a SystemExit with the return value if it
61 returns, pass along any SystemExit it raises, convert
62 KeyboardInterrupts into exit(130), and print a Python 3 style
63 contextual backtrace for other exceptions in both Python 2 and
67 except KeyboardInterrupt as ex:
69 except SystemExit as ex:
71 except BaseException as ex:
79 # Excepting wrap_main() in the traceback, these should produce similar output:
80 # python2 lib/bup/compat.py
81 # python3 lib/bup/compat.py
83 # diff -u <(python2 lib/bup/compat.py 2>&1) <(python3 lib/bup/compat.py 2>&1)
85 # Though the python3 output for 'second' will include a stacktrace
86 # starting from wrap_main, rather than from outer().
88 if __name__ == '__main__':
91 raise Exception('first')
96 except Exception as ex:
99 raise Exception('second')
100 except Exception as ex2:
101 raise chain_ex(add_ex_tb(ex2), ex)