我想处理AssertionErrors以便向用户隐藏堆栈跟踪的不必要部分,并打印一条消息,说明发生错误的原因以及用户应采取的措施。
AssertionError
有什么办法可以找出assert该except块中失败的行或语句?
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语句中:
assert 7 == 7, "7 == 7"
因为它会重复信息。
使用回溯模块:
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)