这篇文章主要介绍了基于python traceback实现异常的获取与处理,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
1、traceback.print_exc()
2、traceback.format_exc()
3、traceback.print_exception()
简单说下这三个方法是做什么用的:
1、print_exc():是对异常栈输出
2、format_exc():是把异常栈以字符串的形式返回,print(traceback.format_exc()) 就相当于traceback.print_exc()
3、print_exception():traceback.print_exc()实现方式就是traceback.print_exception(sys.exc_info()),可以点sys.exc_info()进
去看看实现
测试代码如下:
def func(a, b): return a / b if __name__ == '__main__': import sys import time import traceback try: func(1, 0) except Exception as e: print('***', type(e), e, '***') time.sleep(2) print("***traceback.print_exc():*** ") time.sleep(1) traceback.print_exc() time.sleep(2) print("***traceback.format_exc():*** ") time.sleep(1) print(traceback.format_exc()) time.sleep(2) print("***traceback.print_exception():*** ") time.sleep(1) traceback.print_exception(*sys.exc_info())
运行结果:
*** <class 'ZeroDivisionError'> division by zero *** ***traceback.print_exc():*** Traceback (most recent call last): File "E:/HttpRunnerManager-jh/ApiManager/tests.py", line 42, in <module> func(1, 0) File "E:/HttpRunnerManager-jh/ApiManager/tests.py", line 33, in func return a / b ZeroDivisionError: division by zero ***traceback.format_exc():*** Traceback (most recent call last): File "E:/HttpRunnerManager-jh/ApiManager/tests.py", line 42, in <module> func(1, 0) File "E:/HttpRunnerManager-jh/ApiManager/tests.py", line 33, in func return a / b ZeroDivisionError: division by zero ***traceback.print_exception():*** Traceback (most recent call last): File "E:/HttpRunnerManager-jh/ApiManager/tests.py", line 42, in <module> func(1, 0) File "E:/HttpRunnerManager-jh/ApiManager/tests.py", line 33, in func return a / b ZeroDivisionError: division by zero
可以看出,三种方式打印结果是一样的。在开发时,做调试是很方便的。也可以把这种异常栈写入日志。
logging.exception(ex) # 指名输出栈踪迹, logging.exception的内部也是包了一层此做法 logging.error(ex, exc_info=1) # 更加严重的错误级别 logging.critical(ex, exc_info=1) # 我直接copy的,未尝试。有时间会试下的
python 还有一个模块叫cgitb,输出的error非常详情。
try: func(1, 0) except Exception as e: import cgitb cgitb.enable(format='text') func(1, 0)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com
暂无评论...
更新日志
2024年09月23日
2024年09月23日
- 梁汉文2008-EDMONDHITS48[香港]3CD[WAV+CUE]
- 国风大师纯音系列《童丽-[渭城曲]》1CD[WAV分轨][593.5MB]
- 国风大师纯音系列《许菱子《烧筝2》古筝曲集》1CD[WAV分轨][1.3GB]
- 王子异《1996 Part.2》[320K/MP3][18.29MB]
- 群星.1994-宝丽金最倾情3CD【宝丽金】【WAV+CUE】
- 乐俊亨.2024-同泪【CharioticMusic】【FLAC分轨】
- 何耀珊.2006-收获【华纳】【WAV+CUE】
- 梁汉文1994-壹精选[华星][WAV+CUE]
- 洪荣宏1981-歹路不可行·相思雨(飞跃复刻版)[光美][WAV+CUE]
- 旅行团2015-10Day’s[来福胶泥][WAV+CUE]
- 龙千玉.2011-卡将哟【豪记】【WAV+CUE】
- 蔣志光.1993-多情多寂寞(国专)【BMG】【WAV+CUE】
- 陈慧娴.1996-雪映美白96演唱会2CD(2024环球红馆40复刻系列)【环球】【WAV+CUE】
- 王子异《1996 Part.2》[FLAC/分轨][50.66MB]
- 贵族音乐《古典名曲与轻音乐钢琴 打开宝宝睡眠开关》[320K/MP3][155.91MB]