【问题标题】:Automatically print the next line variable for debugging purpose自动打印下一行变量以进行调试
【发布时间】:2020-05-30 16:25:35
【问题描述】:

在调试复杂代码时,有时需要进行改造:

def myfunction(self):
    ...
    self.foo.bar = self.baz.bla

进入

def myfunction(self):
    ...
    self.foo.bar = self.baz.bla
    print("myfunction", "self.foo.bar", self.foo.bar)  # add this for debugging purposes

有没有办法(使用装饰器或上下文管理器或其他任何东西)自动print 变量名和下一行代码赋值的值(也可能是当前函数)?强>

例子:

def myfunction(self):
    ...
    with debug:
        self.foo.bar = self.baz.bla

会输出:

 "myfunction self.foo.bar 123"

【问题讨论】:

    标签: python debugging logging contextmanager


    【解决方案1】:

    您可以使用检查模块:

    from inspect import currentframe
    
    def f():
        a = 5
        debug_print("a")
    
    def debug_print(var):
        locals = currentframe().f_back.f_locals
        print(f"{var} = {locals[var]}")
    
    f()
    

    参见此处:Access parent namespace in python

    我承认,这只是你所问的一部分,但也许是一个好的开始。

    编辑:好的,这样呢:

    from inspect import currentframe, getsourcelines
    
    class A:
        def f(self):
            self.b = 5
            debug_print()
            self.a = A()
            self.a.a = 4
            debug_print()
    
        @staticmethod
        def g():
            A.c = 5
            debug_print()
    
    def debug_print():
        frame = currentframe().f_back
        locals = frame.f_locals
        globals = frame.f_globals
        source, start = getsourcelines(currentframe().f_back.f_code)
        var_name = source[frame.f_lineno - 1 - start].split("=")[0]
        tokens = var_name.strip().split(".")
        var = locals.get(tokens[0], globals.get(tokens[0], None))
        for t in tokens[1:]:
            var = getattr(var, t)
        print(f"{var_name} = {var}")
    
    a = A()
    a.f()
    a.g()
    

    至少现在,它适用于成员属性(包括self),甚至是嵌套的。还可以为类分配全局变量,例如静态属性。

    【讨论】:

    • 谢谢!我希望能够做到这一点不必重写变量名。只需debug_last_line()。这可能吗?
    • 很好的解决方案,谢谢! PS:它不适用于课程,例如class Test: def do(self): self.blah = 123 debug_print(),但inspect 肯定有一些东西可以做到这一点!
    • 好的,我们到了。 ;-)。当然,它还远未普及……接下来你要的是数组:field[2] = ...,但我想我把这个练习留给读者;-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-14
    • 1970-01-01
    • 2013-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多