这几天写python代码忽然想到各种语言都有一些基础库,python应该也有,在网上搜索到一个boltons库,说里面有好多基础功能。可惜的是光有说明没有范例。
随便看一个异常类,通过摸索发现果然是一个好东西,比traceback好用一些,可以打印出出错堆栈,出错的代码行,出错的具体代码和出错的消息。
使用前需:pip3 install boltons 安装此库
当程序发生异常时,通过如下代码可得到对应的出错信息:
ExceptionInfo.from_current().get_formatted()
完整代码如下:
from boltons.tbutils import ExceptionInfo
a = 0
b = 10
print("****************** begin...")
try:
c = b / a
print(c)
except Exception as exception:
print("{}".format(ExceptionInfo.from_current().get_formatted()))
print("****************** end.")
程序运行结果如下: