小编典典

如何在Python中处理AssertionError并找出发生在哪一行或语句上?

python

我想处理AssertionErrors以便向用户隐藏堆栈跟踪的不必要部分,并打印一条消息,说明发生错误的原因以及用户应采取的措施。

有什么办法可以找出assertexcept块中失败的行或语句?

try:
    assert True
    assert 7 == 7
    assert 1 == 2
    # many more statements like this
except AssertionError:
    print 'Houston, we have a problem.'
    print
    print 'An error occurred on line ???? in statement ???'
    exit(1)

我不想将其添加到每个assert语句中:

assert 7 == 7, "7 == 7"

因为它会重复信息。


阅读 176

收藏
2021-01-20

共1个答案

小编典典

使用回溯模块:

import sys
import traceback

try:
    assert True
    assert 7 == 7
    assert 1 == 2
    # many more statements like this
except AssertionError:
    _, _, tb = sys.exc_info()
    traceback.print_tb(tb) # Fixed format
    tb_info = traceback.extract_tb(tb)
    filename, line, func, text = tb_info[-1]

    print('An error occurred on line {} in statement {}'.format(line, text))
    exit(1)
2021-01-20