|
| 1 | +try: |
| 2 | + from typing import List |
| 3 | +except ImportError: |
| 4 | + pass |
| 5 | + |
| 6 | +import sys |
| 7 | + |
| 8 | + |
| 9 | +def _print_err(*args): |
| 10 | + print(*args, file=sys.stderr) |
| 11 | + |
| 12 | + |
| 13 | +def _print_traceback(traceback, limit=None) -> List[str]: |
| 14 | + if limit is None: |
| 15 | + if hasattr(sys, "tracebacklimit"): |
| 16 | + limit = sys.tracebacklimit |
| 17 | + |
| 18 | + n = 0 |
| 19 | + while traceback is not None: |
| 20 | + frame = traceback.tb_frame |
| 21 | + line_number = traceback.tb_lineno |
| 22 | + frame_code = frame.f_code |
| 23 | + filename = frame_code.co_filename |
| 24 | + name = frame_code.co_name |
| 25 | + _print_err(' File "%s", line %d, in %s' % (filename, line_number, name)) |
| 26 | + traceback = traceback.tb_next |
| 27 | + n = n + 1 |
| 28 | + if limit is not None and n >= limit: |
| 29 | + break |
| 30 | + |
| 31 | + |
| 32 | +def print_exception(exception, value, traceback): |
| 33 | + if traceback: |
| 34 | + _print_err("Traceback (most recent call last):") |
| 35 | + _print_traceback(traceback) |
| 36 | + |
| 37 | + if isinstance(exception, Exception) or isinstance(exception, BaseException): |
| 38 | + exception_type = type(exception).__name__ |
| 39 | + elif hasattr(exception, "__name__"): |
| 40 | + exception_type = exception.__name__ |
| 41 | + else: |
| 42 | + exception_type = type(value).__name__ |
| 43 | + |
| 44 | + valuestr = str(value) |
| 45 | + if value is None or not valuestr: |
| 46 | + _print_err(exception_type) |
| 47 | + else: |
| 48 | + _print_err("%s: %s" % (str(exception_type), valuestr)) |
0 commit comments