在Python(3.10)中,一个异常在try
中引发,包含一个不会扩展到try
的调用位置的回溯.
这对我来说有点令人惊讶,更重要的是,这不是我想要的.
这里有一个简短的程序来说明这个问题:
# short_tb.py
import traceback
def caller():
somefunction()
def somefunction():
try:
raise ValueError("This is a value error")
except ValueError as e:
# in my actual code, e is passed to a function, and __traceback__ is pulled from it for logging at this other
# location; the code below simply demonstrates the lack of frames in the traceback object
print("".join(traceback.format_tb(e.__traceback__)))
print("This will produce a traceback with only one frame, the one in somefunction()")
caller()
def caller2():
somefunction2()
def somefunction2():
raise ValueError("This is a value error")
print("This will produce a traceback with all relevant frames (the default behavior of the python interpreter)")
caller2()
输出:
This will produce a traceback with only one frame, the one in somefunction()
File ".../short_tb.py", line 10, in somefunction
raise ValueError("This is a value error")
This will produce a traceback with all relevant frames (the default behavior of the python interpreter)
Traceback (most recent call last):
File ".../short_tb.py", line 30, in <module>
caller2()
File ".../short_tb.py", line 22, in caller2
somefunction2()
File ".../short_tb.py", line 26, in somefunction2
raise ValueError("This is a value error")
ValueError: This is a value error
我希望__traceback__
包含第二个例子中的所有信息.我很高兴覆盖变量,我可以在异常处理位置这样做.但是我如何才能得到一个对象来实现这个目的呢?
在这个问题中,有很多关于追溯的答案,但似乎没有一个是关于traceback objects
的:
Catch and print full Python exception traceback without halting/exiting the program个