用Python装饰器给函数自动加上try except
用装饰器实现把函数用try...except包起来:
import logging import traceback from functools import wraps logging.basicConfig(filename='error.log', level=logging.INFO, format='%(levelname)s::%(name)s::%(asctime)s::%(filename)s,line %(lineno)s, in %(funcName)s(),msg:%(message)s' ) #定义装饰器error_handler def error_handler(func): @wraps(func) #关键行 def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except: msg=traceback.format_exc() logging.error(msg) return 'error' return wrapper #返回函数名 #用法示例:自动处理test()的异常 @error_handler def test(): a=1/0 return a if __name__=='__main__': test()
不需要wraps的写法:
def timeit(func): def wrapper(*args,**kwargs): start=time.time() print('{}:{}() started.'.format(get_now_str(),func.__name__)) res=func(*args,**kwargs) end=time.time() print('{}:{}() ended.'.format(get_now_str(),func.__name__)) print('time elapsed:{:.4f} seconds.'.format(end-start)) return res return wrapper