Printing an exception that works on Micropython/CircuitPython AND desktop python

25 Views Asked by At

I am writing a library that is supposed to work on Micropython/CircuitPython as well as on "normal" Python (i.e, like a Raspberry Pi). I have not been able to find a way to format or print exceptions with a stack trace that works on both!

I have tried:

...
except Exception:
    print(traceback.format_exc())

... which runs on desktop (Python 3.8.10), but on CircuitPython I get an AttributeError.

And I've tried:

...
except Exception as e:
    print(traceback.format_exception(e))

...which runs on CircuitPython, but on desktop I get: TypeError: format_exception() missing 2 required positional arguments: 'value' and 'tb'

And I've tried:

...
except Exception:
    print(sys.exc_info()[2])

...which runs on my desktop, but on CircuitPython I get another attribute error.

I've also tried the print equivalents of the above format functions. I've also tried everything on this StackOverflow. And here. And here. I would ideally like to do this without defining a utility function that switches between MicroPython and desktop code -- A simple one-liner seems appropriate for a task like this.

0

There are 0 best solutions below