Hi,
The docs say that a TracebackException’s stack attribute is a stack summary but it seems to be only a frame.
How can I get the stack from the tbe?
I would like to save a TracebackException object in one process and log a stack trace later in another.
The snippet below prints tbe.stack=[<FrameSummary file /home/pete/src/xpack/t.py, line 5 in b>]
Similarly, traceback.TracebackException.from_exception(e).format() does not include function a; however traceback.format_stack() has both a and b.
I am not an expert on the python stack and exception machinery so probably I am missing something obvious. A solution or workaround would be greatly appreciated.
Thank you!!
Thanks for the info Elis; after a bit more digging I found an old blog post and a SO thread, and came up with this solution, which works for me and hopefully others may find useful.
import sys
import traceback
def b():
try:
1/0
except Exception as e:
tbe = traceback.TracebackException.from_exception(e)
print(f"Local {''.join(tbe.format())}")
f = sys.exc_info()[2].tb_frame
f = f.f_back
while f is not None:
tbe.stack.append(traceback.FrameSummary(
f.f_code.co_filename, f.f_lineno, f.f_code.co_name))
f = f.f_back
print()
print(f"Full {''.join(tbe.format())}")
def a():
b()
a()
Output:
$ python t.py
Local Traceback (most recent call last):
File "/home/pete/src/xpack/t.py", line 6, in b
1/0
~^~
ZeroDivisionError: division by zero
Full Traceback (most recent call last):
File "/home/pete/src/xpack/t.py", line 6, in b
1/0
~^~
File "/home/pete/src/xpack/t.py", line 21, in a
b()
File "/home/pete/src/xpack/t.py", line 23, in <module>
a()
ZeroDivisionError: division by zero