python 处理异常的方法,try except 封装装饰器
import sys
import traceback
from functools import wraps
from datetime import datetime
def except_output(func):
@wraps(func)
def execept_print(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
sign = '=' * 60 + '\n'
tb=e.__traceback__
tb=find_error_func(tb)
print(f'{sign}>>>异常时间:\t{datetime.now()}\n>>>异常函数及行数:\t该{tb.tb_frame.f_code.co_name}函数的-->第{tb.tb_lineno}行\n>>>异常函数所在文件:\t{tb.tb_frame.f_code.co_filename}')
print(f'{"=" * 24}异常详细原因{"=" * 24}\n{traceback.format_exc()}{sign}')
return execept_print
def find_error_func(e):
file_list=['definition.py','exception_handling.py','genDDS.py','idlparser.py','Process_Idl.py','Serializer_Parser.py','grammar.lark']
e=e.tb_next
if e.tb_next.tb_frame.f_code.co_filename.split('/')[-1] not in file_list:
return e
else:
e=e.tb_next
return find_error_func(e)