75

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

有什么方法可以找出块assert内失败的行或语句except

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"

因为它重复信息。

4

2 回答 2

83

使用回溯模块:

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)
于 2012-07-20T21:37:03.310 回答
36

traceback 模块和 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)
于 2017-08-17T09:10:13.850 回答