简体   繁体   English

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

[英]Python Decorator for printing every line executed by a function

I want to, for debugging purposes, print out something pertaining to each and every line executed in a python method. 我想,为了调试目的,打印出与python方法中执行的每一行有关的内容。

For example if there was some assignment in the line, i want to print what value was assigned for that variable, and if there was a function call, i want to print out the value returned by the function, etc. 例如,如果行中有一些赋值,我想打印为该变量赋值的值,如果有函数调用,我想打印出函数返回的值等。

So, for example if i were to use a decorator, applied on function/method such as : 所以,例如,如果我使用装饰器,应用于函数/方法,如:

@some_decorator
def testing() : 
    a = 10
    b = 20
    c = a + b
    e = test_function()

the function testing when called, should print the following : 调用函数测试时,应打印以下内容:

a = 10
b = 20  
c = 30
e = some_value

Is there some way to achieve this? 有没有办法实现这个目标? More fundamentally, i want to know whether i can write a code that can go through some other code line by line, check what type of an instruction it is, etc. Or maybe like we can get a dictionary for finding out all the variables in a class, can i get a dictionary like datastructure for getting every instruction in a function, which is as good a metaprogram can get. 更基本的是,我想知道我是否可以编写一个可以逐行查看其他代码的代码,检查它是什么类型的指令,等等。或者就像我们可以得到一个字典来查找所有变量一个类,我可以得到像数据结构这样的字典来获取函数中的每个指令,这是一个好的元程序可以得到的。

Hence, I am particularly looking a solution using decorators, as I am curious if one can have a decorator that can go through an entire function line by line, and decorate it line by line, but any and all solutions are welcome. 因此,我特别期待使用装饰器的解决方案,因为我很好奇是否可以拥有可以逐行完成整个功能的装饰器,并逐行装饰,但欢迎任何和所有解决方案。

Thanks in advance. 提前致谢。

How about something like this? 这样的事怎么样? Would this work for you? 这对你有用吗?

Debug Context: 调试上下文:

import sys

class 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_code.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_code
        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))

Debug Decorator: 调试装饰器:

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

Usage 用法

@debug_decorator
def testing() : 
    a = 10
    b = 20
    c = a + b

testing()

Output 产量

###########################################################
#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}
###########################################################

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM