【问题标题】:How to hide the last call from traceback?如何隐藏回溯的最后一次调用?
【发布时间】:2021-07-26 17:37:30
【问题描述】:

我有以下代码

def _raise_exception(exception):
    raise exception

def require_odd(n):
    if n % 2 == 0:
        _raise_exception(ValueError("n must be odd"))

print(require_odd(2))

当我运行它时,它会显示

Traceback (most recent call last):
  File "main.py", line 31, in <module>
    print(require_odd(2))
  File "main.py", line 29, in require_odd
    _raise_exception(ValueError("n must be odd"))
  File "main.py", line 25, in _raise_exception
    raise exception
ValueError: n must be odd

由于回溯的最后一行代码是多余的,我该如何引发异常以使其显示以下内容?

Traceback (most recent call last):
  File "main.py", line 31, in <module>
    print(require_odd(2))
ValueError: n must be odd

目前,我正在这样做:

def _raise_exception(exception):
    try:
        raise exception
    except Exception as e:
        # Remove the last two calls (from this function and from the caller of this function)
        stack_lines = traceback.format_stack()[:-2]

        # Get the exception lines that contains the "Traceback (most recent call last):" in
        # the first line and the "ValueError: n must be odd" in the last line
        exception_lines = traceback.format_exception(e.__class__, e, e.__traceback__)

        # Join the relevant lines, print to stderr and exit
        print(''.join(exception_lines[:1] + stack_lines + exception_lines[-1:]), file=sys.stderr)
        exit(1)

def require_odd(n):
    if n % 2 == 0:
        _raise_exception(ValueError("n must be odd"))

print(require_odd(2))

确实可以打印

Traceback (most recent call last):
  File "main.py", line 31, in <module>
    print(require_odd(2))
ValueError: n must be odd

但它只是感觉临时。有没有更好的办法?

【问题讨论】:

  • 我不确定您所说的“冗余”是什么意思。堆栈跟踪是人们希望的功能 - 它正在转储整个调用堆栈。这通常被认为是好事,Python 运行时会遇到很多麻烦才能为您提供这些信息...

标签: python error-handling traceback


【解决方案1】:

你不能去掉_raise_exception 函数吗?

如果你只是跑

if n % 2 == 0: 
    raise ValueError("n must be odd") 

这将消除最后一行,以及该过程中不必要的步骤。它不会消除中间线,但一般来说,最佳实践(我知道)是不理会堆栈。当出现问题时,您需要尽可能多的数据。

如果我遗漏了什么,请告诉我,我会更新。

【讨论】:

  • 正如你所说,这将添加一个raise ValueError("n must be odd") 行,我认为这是多余的,因为异常的最后一行是ValueError: n must be odd,但如果没有更好的选择,我想我会有处理它。
  • 制作一些用户不喜欢“漂亮”的东西似乎需要做很多工作。这有点多余,但同样,它提供了更多信息。如果您要在更长的堆栈中搜索错误,那么冗余将有助于更容易吸引您的眼球。
猜你喜欢
  • 2022-01-10
  • 1970-01-01
  • 1970-01-01
  • 2013-10-13
  • 2022-07-07
  • 1970-01-01
  • 1970-01-01
  • 2019-04-01
  • 1970-01-01
相关资源
最近更新 更多