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

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

问题描述

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

有什么方法可以找出 assertexcept 块中的哪一行或哪条语句失败?

尝试:断言真断言 7 == 7断言 1 == 2# 还有更多这样的语句除了断言错误:打印休斯顿,我们遇到了问题."打印打印'在线出错????在声明中???"退出(1)

我不想把这个添加到每个断言语句中:

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

因为它重复信息.

解决方案

使用 traceback 模块:>

导入系统导入回溯尝试:断言真断言 7 == 7断言 1 == 2# 还有更多这样的语句除了断言错误:_, _, tb = sys.exc_info()traceback.print_tb(tb) # 固定格式tb_info = traceback.extract_tb(tb)文件名、行、函数、文本 = tb_info[-1]print('在语句 {} 中的行 {} 上发生错误'.format(line, text))退出(1)

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.

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)

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

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

because it repeats information.

解决方案

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天全站免登陆