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(), chain_ex(), etc.
9 py_maj = sys.version_info[0]
14 from shlex import quote
19 """Do nothing (already handled by Python 3 infrastructure)."""
22 def chain_ex(ex, context_ex):
23 """Do nothing (already handled by Python 3 infrastructure)."""
31 from pipes import quote
36 """Add a traceback to ex if it doesn't already have one. Return ex.
39 if not getattr(ex, '__traceback__', None):
40 ex.__traceback__ = sys.exc_info()[2]
43 def chain_ex(ex, context_ex):
44 """Chain context_ex to ex as the __context__ (unless it already has
49 if not getattr(ex, '__context__', None):
50 ex.__context__ = context_ex
53 def dump_traceback(ex):
55 next_ex = getattr(ex, '__context__', None)
58 next_ex = getattr(next_ex, '__context__', None)
59 stack = reversed(stack)
61 tb = getattr(ex, '__traceback__', None)
62 print_exception(type(ex), ex, tb)
64 print('\nDuring handling of the above exception, another exception occurred:\n',
66 tb = getattr(ex, '__traceback__', None)
67 print_exception(type(ex), ex, tb)
74 """Run main() and raise a SystemExit with the return value if it
75 returns, pass along any SystemExit it raises, convert
76 KeyboardInterrupts into exit(130), and print a Python 3 style
77 contextual backtrace for other exceptions in both Python 2 and
81 except KeyboardInterrupt as ex:
83 except SystemExit as ex:
85 except BaseException as ex:
93 # Excepting wrap_main() in the traceback, these should produce similar output:
94 # python2 lib/bup/compat.py
95 # python3 lib/bup/compat.py
97 # diff -u <(python2 lib/bup/compat.py 2>&1) <(python3 lib/bup/compat.py 2>&1)
99 # Though the python3 output for 'second' will include a stacktrace
100 # starting from wrap_main, rather than from outer().
102 if __name__ == '__main__':
105 raise Exception('first')
110 except Exception as ex:
113 raise Exception('second')
114 except Exception as ex2:
115 raise chain_ex(add_ex_tb(ex2), ex)