|
| 1 | +# SPDX-FileCopyrightText: 2019-2020 Damien P. George |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: MIT |
| 4 | +# |
| 5 | +# MicroPython uasyncio module |
| 6 | +# MIT license; Copyright (c) 2019-2020 Damien P. George |
| 7 | +""" |
| 8 | +Fallback traceback module if the system traceback is missing. |
| 9 | +""" |
| 10 | + |
| 11 | +try: |
| 12 | + from typing import List |
| 13 | +except ImportError: |
| 14 | + pass |
| 15 | + |
| 16 | +import sys |
| 17 | + |
| 18 | + |
| 19 | +def _print_traceback(traceback, limit=None, file=sys.stderr) -> List[str]: |
| 20 | + if limit is None: |
| 21 | + if hasattr(sys, "tracebacklimit"): |
| 22 | + limit = sys.tracebacklimit |
| 23 | + |
| 24 | + n = 0 |
| 25 | + while traceback is not None: |
| 26 | + frame = traceback.tb_frame |
| 27 | + line_number = traceback.tb_lineno |
| 28 | + frame_code = frame.f_code |
| 29 | + filename = frame_code.co_filename |
| 30 | + name = frame_code.co_name |
| 31 | + print(' File "%s", line %d, in %s' % (filename, line_number, name), file=file) |
| 32 | + traceback = traceback.tb_next |
| 33 | + n = n + 1 |
| 34 | + if limit is not None and n >= limit: |
| 35 | + break |
| 36 | + |
| 37 | + |
| 38 | +def print_exception(exception, value=None, traceback=None, limit=None, file=sys.stderr): |
| 39 | + """ |
| 40 | + Print exception information and stack trace to file. |
| 41 | + """ |
| 42 | + if traceback: |
| 43 | + print("Traceback (most recent call last):", file=file) |
| 44 | + _print_traceback(traceback, limit=limit, file=file) |
| 45 | + |
| 46 | + if isinstance(exception, BaseException): |
| 47 | + exception_type = type(exception).__name__ |
| 48 | + elif hasattr(exception, "__name__"): |
| 49 | + exception_type = exception.__name__ |
| 50 | + else: |
| 51 | + exception_type = type(value).__name__ |
| 52 | + |
| 53 | + valuestr = str(value) |
| 54 | + if value is None or not valuestr: |
| 55 | + print(exception_type, file=file) |
| 56 | + else: |
| 57 | + print("%s: %s" % (str(exception_type), valuestr), file=file) |
0 commit comments