参考链接:https://blog.youkuaiyun.com/lengxingxing_/article/details/56317838
https://segmentfault.com/a/1190000012625548
一、利用traceback模块手自定义处理异常
1、第一种解析方式
'''1 第一种解析方式'''
def f():
1 / 0
try:
f()
except:
a, b, c = sys.exc_info()
print(a, b, c)
for filename, linenum, funcname, source in traceback.extract_tb(c):
print(filename, linenum, funcname, source)
输出结果为
<class 'ZeroDivisionError'> division by zero <traceback object at 0x7f3688e96c48>
/home/duxin/surfing/surfing_code/python-cron/sf_crontab/test/python异常和上下文协议/python_exception.py 12 <module> f()
/home/duxin/surfing/surfing_code/python-cron/sf_crontab/test/python异常和上下文协议/python_exception.py 7 f 1 / 0
2、第二种解析方式
'''2 第二中解析方式'''
try:
f()
except:
a, b, c = sys.exc_info()
print(a, b, c)
print(traceback.print_exception(a, b, c))
输出结果:
Traceback (most recent call last):
<class 'ZeroDivisionError'> division by zero <traceback object at 0x7fc5a6652d08>
None
File "/home/duxin/surfing/surfing_code/python-cron/sf_crontab/test/python异常和上下文协议/python_exception.py", line 32, in <module>
f()
File "/home/duxin/surfing/surfing_code/python-cron/sf_crontab/test/python异常和上下文协议/python_exception.py", line 7, in f
1 / 0
ZeroDivisionError: division by zero
3、第三种解析
'''3、 cgitb的使用'''
cgitb.enable(context=3, format='text') # 可以定义异常文件的的保存位置、保存文件的类型
f()
cgitb的两个方法
cgitb.encable(display=1, logdir=None, context=5, format="html")
display 1,发送至浏览器;0, 不发送
logdir 如果有的话,写到该目录下
context 显示错误代码周围的代码行数
format 是否显示为HTML,除了'html'之外的所有值,都会显示为纯文本
cgitb.handle(info=None)
如果你想用cgitb处理异常,你可以调用这个函数。
info 应当是含有异常类型、异常值和traceback对象的三元组,——如同sys.exc_info()返回的那样。如果不提供info,则从sys.exc_info中获取。
输出结果:
ZeroDivisionError
Python 3.6.7: /usr/bin/python3.6
Sun Apr 28 11:50:09 2019
A problem occurred in a Python script. Here is the sequence of
function calls leading up to the error, in the order they occurred.
/home/duxin/surfing/surfing_code/python-cron/sf_crontab/test/python异常和上下文协议/python_exception.py in <module>()
49 cgitb.enable(context=3, format='text') # 可以定义异常文件的的保存位置、保存文件的类型
50 f()
51
f = <function f>
/home/duxin/surfing/surfing_code/python-cron/sf_crontab/test/python异常和上下文协议/python_exception.py in f()
6 def f():
7 1 / 0
8
ZeroDivisionError: division by zero
__cause__ = None
__class__ = <class 'ZeroDivisionError'>
__context__ = None
__delattr__ = <method-wrapper '__delattr__' of ZeroDivisionError object>
__dict__ = {}
__dir__ = <built-in method __dir__ of ZeroDivisionError object>
__doc__ = 'Second argument to a division or modulo operation was zero.'
__eq__ = <method-wrapper '__eq__' of ZeroDivisionError object>
__format__ = <built-in method __format__ of ZeroDivisionError object>
__ge__ = <method-wrapper '__ge__' of ZeroDivisionError object>
__getattribute__ = <method-wrapper '__getattribute__' of ZeroDivisionError object>
__gt__ = <method-wrapper '__gt__' of ZeroDivisionError object>
__hash__ = <method-wrapper '__hash__' of ZeroDivisionError object>
__init__ = <method-wrapper '__init__' of ZeroDivisionError object>
__init_subclass__ = <built-in method __init_subclass__ of type object>
__le__ = <method-wrapper '__le__' of ZeroDivisionError object>
__lt__ = <method-wrapper '__lt__' of ZeroDivisionError object>
__ne__ = <method-wrapper '__ne__' of ZeroDivisionError object>
__new__ = <built-in method __new__ of type object>
__reduce__ = <built-in method __reduce__ of ZeroDivisionError object>
__reduce_ex__ = <built-in method __reduce_ex__ of ZeroDivisionError object>
__repr__ = <method-wrapper '__repr__' of ZeroDivisionError object>
__setattr__ = <method-wrapper '__setattr__' of ZeroDivisionError object>
__setstate__ = <built-in method __setstate__ of ZeroDivisionError object>
__sizeof__ = <built-in method __sizeof__ of ZeroDivisionError object>
__str__ = <method-wrapper '__str__' of ZeroDivisionError object>
__subclasshook__ = <built-in method __subclasshook__ of type object>
__suppress_context__ = False
__traceback__ = <traceback object>
args = ('division by zero',)
with_traceback = <built-in method with_traceback of ZeroDivisionError object>
The above is a description of an error in a Python program. Here is
the original traceback:
Traceback (most recent call last):
File "/home/duxin/surfing/surfing_code/python-cron/sf_crontab/test/python异常和上下文协议/python_exception.py", line 50, in <module>
f()
File "/home/duxin/surfing/surfing_code/python-cron/sf_crontab/test/python异常和上下文协议/python_exception.py", line 7, in f
1 / 0
ZeroDivisionError: division by zero
4、自定义异常处理
def my_exception_handler(exc_type, exc_value, exc_tb):
print("i caught the exception:", exc_type, exc_value)
while exc_tb:
print("the line no:", exc_tb.tb_lineno)
print("the frame locals:", exc_tb.tb_frame.f_locals)
exc_tb = exc_tb.tb_next
sys.excepthook = my_exception_handler
f()
输出结果
i caught the exception: <class 'ZeroDivisionError'> division by zero
the line no: 141
the frame locals: {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f75cb346278>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/duxin/surfing/surfing_code/python-cron/sf_crontab/test/python异常和上下文协议/python_exception.py', '__cached__': None, 'cgitb': <module 'cgitb' from '/usr/lib/python3.6/cgitb.py'>, 'sys': <module 'sys' (built-in)>, 'traceback': <module 'traceback' from '/usr/lib/python3.6/traceback.py'>, 'f': <function f at 0x7f75cb36cea0>, 'a': <class 'ZeroDivisionError'>, 'b': ZeroDivisionError('division by zero',), 'c': <traceback object at 0x7f75c918b5c8>, 'my_exception_handler': <function my_exception_handler at 0x7f75c9198ea0>}
the line no: 7
the frame locals: {}
当有变量时,the frame locals: {} 的大括号中会以 变量名:变量值 的方式显示出来