栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python Decorator用于打印函数执行的每一行

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python Decorator用于打印函数执行的每一行

这样的事情怎么样?这对您有用吗?

调试上下文:

import sysclass debug_context():    """ Debug context to trace any function calls inside the context """    def __init__(self, name):        self.name = name    def __enter__(self):        print('Entering Debug Decorated func')        # Set the trace function to the trace_calls function        # So all events are now traced        sys.settrace(self.trace_calls)    def __exit__(self, *args, **kwargs):        # Stop tracing all events        sys.settrace = None    def trace_calls(self, frame, event, arg):         # We want to only trace our call to the decorated function        if event != 'call': return        elif frame.f_pre.co_name != self.name: return        # return the trace function to use when you go into that         # function call        return self.trace_lines    def trace_lines(self, frame, event, arg):        # If you want to print local variables each line        # keep the check for the event 'line'        # If you want to print local variables only on return        # check only for the 'return' event        if event not in ['line', 'return']: return        co = frame.f_pre        func_name = co.co_name        line_no = frame.f_lineno        filename = co.co_filename        local_vars = frame.f_locals        print ('  {0} {1} {2} locals: {3}'.format(func_name,       event,      line_no,       local_vars))

调试装饰器:

def debug_decorator(func):    """ Debug decorator to call the function within the debug context """    def decorated_func(*args, **kwargs):        with debug_context(func.__name__): return_value = func(*args, **kwargs)        return return_value    return decorated_func

用法

@debug_decoratordef testing() :     a = 10    b = 20    c = a + btesting()

输出量

############################################################output:#   Entering Debug Decorated func#     testing line 44 locals: {}#     testing line 45 locals: {'a': 10}#     testing line 46 locals: {'a': 10, 'b': 20}#     testing return 46 locals: {'a': 10, 'b': 20, 'c': 30}###########################################################


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/648938.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号