如何在Python中处理AssertionError并找出发生在哪一行或语句上? [英] How to handle AssertionError in Python and find out which line or statement it occurred on?

查看:653
本文介绍了如何在Python中处理AssertionError并找出发生在哪一行或语句上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to handle AssertionErrors both to hide unnecessary parts of the stack trace from the user and to print a message as to why the error occurred and what the user should do about it.

是否可以找到在except块中assert失败的行或语句?

Is there any way to find out on which line or statement the assert failed within the except block?

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语句中:

I don't want to have to add this to every assert statement:

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

因为它重复了信息.

推荐答案

使用 traceback 模块:

Use the traceback module:

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)

这篇关于如何在Python中处理AssertionError并找出发生在哪一行或语句上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆