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

dev*_*vtk 50 python assert

我想处理AssertionError两者以隐藏用户的堆栈跟踪的不必要部分,并打印一条消息,说明错误发生的原因以及用户应该做些什么.

有没有办法找出块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)
Run Code Online (Sandbox Code Playgroud)

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

assert 7 == 7, "7 == 7"
Run Code Online (Sandbox Code Playgroud)

因为它重复信息.

phi*_*hag 64

使用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)
Run Code Online (Sandbox Code Playgroud)


not*_*ter 20

跟踪模块和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
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

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

import logging

try:
    assert False == True 
except AssertionError:
    logging.error("Nothing is real but I can't quit...", exc_info=True)
Run Code Online (Sandbox Code Playgroud)