← index #4667PR #11244
Related · high · value 3.838
QUERY · ISSUE

Print traceback without an exception

openby mzakharocscopened 2019-04-02updated 2019-05-14

Hello, in CPython, there is a way to print a traceback outside of an exception, through traceback.print_stack() function. What would it take to add similar functionality to micropython?

CANDIDATE · PULL REQUEST

py/modsys.c: Add sys._exc_traceback.

openby DavidEGraysonopened 2023-04-12updated 2026-03-18
py-core

This new function makes it easier to provide custom formatting of exception stack traces, for example to make them fit on a tiny 16x8-character display. (Without this, I think you'd have to call sys.print_exception, somehow get the output as a string, and then scrape information from that string.)

I'm thinking of this as an experimental function that exposes internal details of MicroPython and therefore might change in the future. That's why it has the underscore in the name.

Here is an example of its output:

['test.py', 4, 'foo', 'test.py', 7, '<module>']

The regular output from sys.print_exception for the same exception is:

Traceback (most recent call last):
  File "test.py", line 7, in <module>
  File "test.py", line 4, in foo
ZeroDivisionError: divide by zero

Both outputs were generated by the following script:

import sys

def foo():
  1/0

try:
  foo()
except Exception as e:
  sys.print_exception(e)
  print(sys._exc_traceback(e))

Is this the right approach for getting info about exception stack traces? I'd be happy to change the name, change the output format, add tests, or add documentation.

Keyboard

j / / n
next pair
k / / p
previous pair
1 / / h
show query pane
2 / / l
show candidate pane
c
copy suggested comment
r
toggle reasoning
g i
go to index
?
show this help
esc
close overlays

press ? or esc to close

copied