如何在不使用 sys.tracebacklimit 的情况下从异常中手动修剪回溯?

问题描述 投票:0回答:1

例子:

>>> 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
python exception error-handling try-catch traceback
1个回答
0
投票

如果是这样呢?通过

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]
           ~~~~~~~^^^
© www.soinside.com 2019 - 2024. All rights reserved.