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

问题描述 投票:48回答:2

我想处理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 7 == 7, "7 == 7"

因为它重复信息。

python assert
2个回答
60
投票

使用traceback模块:

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)

17
投票

跟踪模块和sys.exc_info对于跟踪异常源是过度的。这都是默认的追溯。所以不要再调用exit(1)重新加注:

try:
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
except AssertionError:
    print 'Houston, we have a problem.'
    raise

这给出了以下输出,包括违规语句和行号:

Houston, we have a problem.
Traceback (most recent call last):
  File "/tmp/poop.py", line 2, in <module>
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
AssertionError: Should've asked for pie

类似地,日志记录模块可以轻松记录任何异常(包括捕获且永不重新引发的异常)的回溯:

import logging

try:
    assert False == True 
except AssertionError:
    logging.error("Nothing is real but I can't quit...", exc_info=True)
© www.soinside.com 2019 - 2024. All rights reserved.