Skip to content

Instantly share code, notes, and snippets.

@rswofxd
Created June 8, 2012 08:43
Show Gist options
  • Save rswofxd/2894528 to your computer and use it in GitHub Desktop.
Save rswofxd/2894528 to your computer and use it in GitHub Desktop.
Python:基于装饰器函数实现函数Debug跟踪
#coding:utf-8
#############################
#装饰器:在函数体前后插入执行代码,并完成封装
#利用装饰器函数实现对函数跟踪
#添加装饰器实现Debug调试
#///////////////////////////////////////////////////////////
#from Decorater import trace_func as trace
#///////////////////////////////////////////////////////////
import profile
#############################
#类装饰器风格
#############################
class trace_class(object):
def __init__(self, func):
self.f = func
def __call__(self,*args, **kargs):
print ('===Start with:===\n %s(%s, %s)...' % (self.f.__name__, args, kargs))
print('===Key-Valus:===\n %s' % locals())
print('===Output with:===\n %s' % self.f(*args,**kargs))
print('===Profile Report:===')
profile.run(self.f.__name__)
print('==================================================')
###############################
#函数装饰器风格
###############################
def trace_func(func): #函数入口
"""
A decorate function to track all function invoke information with DEBUG level
Usage:
@trace_func
def any_function(any parametet)
"""
def new_func(*args, **kargs): #函数参数
print ('###Start with:###\n %s(%s, %s)...' % (func.__name__, args, kargs))
print('###Key-Valus:###\n %s' % locals())
print('###Output with:###\n %s' % func(*args,**kargs))
print('###Profile Report:###')
profile.run(func.__name__)
print('==================================================')
return func(*args, **kargs)
return new_func #装饰函数出口
@trace_class
def log_test_with_empty_parameter():
pass
@trace_func
def log_test_with_many_parameter(a_int, b_string, c_list, d_dict):
pass
@trace_func
def log_test_with_key_parameter(a = 'www', b = 1, c = [1,2]):
pass
#######################################
#测试代码
if __name__ == '__main__':
#代码覆盖率测试
import coverage
cov = coverage.coverage()
cov.start()
##################################################
log_test_with_empty_parameter()
log_test_with_many_parameter(1, 'wwww', [1,2,'c'], {1: 'a', 2 : 'ww'})
log_test_with_key_parameter(1, 'wwww', c = [3, 4])
##################################################
cov.stop()
cov.save()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment