0
Follow
0
View

If AssertionError in python [duplicate]

dercat 注册会员
2023-01-25 14:40

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)
sundahai_3 注册会员
2023-01-25 14:40

The traceback module and sys.exc_info are overkill for tracking down the source of an exception. That's all in the default traceback. So instead of calling exit(1) just re-raise:

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

Which gives the following output that includes the offending statement and line number:

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

Similarly the logging module makes it easy to log a traceback for any exception (including those which are caught and never re-raised):

import logging

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

About the Author

Question Info

Publish Time
2023-01-25 14:40
Update Time
2023-01-25 14:40

Related Question

iframe 如何在uniapp上横屏播放

AddDbContextPool和AddInterceptors的问题

python,指定格式化字符串宽度,如何指定

微信小程序引入vant组件,终端输入npm init 出错了

SSAS - modeling cross join

在list - python中访问元组列表中元组的第一个元素

v - code中的Python:无法导入Python文件

Why does windows command prompt keep showing python 3.9.12 even though I've uninstalled all versions of python?

main方法调用方法外的属性

Vmware虚拟机连上了外设网卡,但是无法显示wifi