例子:
>>> def f(): g()
...
>>> def g(): h()
...
>>> def h(): raise Exception
...
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in f
File "<stdin>", line 1, in g
File "<stdin>", line 1, in h
Exception
>>>
我要的是这个:
>>> import sys
>>> sys.tracebacklimit = 1
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in h
Exception
>>>
但我无法在我的案例中使用
sys.tracebacklimit
。有没有其他方法可以在引发异常之前手动修剪回溯?
try:
f()
except Exception as e:
# trim traceback here
raise e
如果是这样呢?通过
sys.exception()
,python 3.11。 医生
import sys, traceback
def lumberjack():
bright_side_of_life()
def bright_side_of_life():
return tuple()[0]
try:
lumberjack()
except IndexError:
exc = sys.exception()
traceback.print_tb(exc.__traceback__, limit=-1, file=sys.stdout)
----------------------------
File "C:\Users\ф\PycharmProjects\tkinter\rrr.py", line 9, in bright_side_of_life
return tuple()[0]
~~~~~~~^^^