【问题标题】:Trace specific functions in Python to capture high-level execution flow跟踪 Python 中的特定函数以捕获高级执行流程
【发布时间】:2021-02-01 01:38:14
【问题描述】:

Python 通过其trace 模块提供跟踪。还有像this 这样的自定义解决方案。但是这些方法捕获了您使用的大多数/每个库的内部和外部的大多数低级执行。除了深入调试之外,这不是很有用。

如果有一些东西只捕获您的管道中布置的最高级别的功能,那就太好了。例如,如果我有:

def funct1():
    res = funct2()
    print(res)

def funct2():
    factor = 3
    res = funct3(factor)
    return(res)

def funct3(factor):
    res = 1 + 100*factor
    return(res)

...并调用:

funct1()

...捕捉一下就好了:

function order:
    - funct1
    - funct2
    - funct3

我看过:

我很乐意手动标记脚本中的函数,就像我们使用 Docstrings 所做的那样。有没有办法给函数添加“钩子”,然后在它们被调用时跟踪它们?

【问题讨论】:

    标签: python trace stack-trace execution


    【解决方案1】:

    您始终可以使用装饰器来跟踪调用了哪些函数。这是一个示例,可让您跟踪调用函数的嵌套级别:

    class Tracker:
        level = 0
    
        def __init__(self, indent=2):
            self.indent = indent
    
        def __call__(self, fn):
            def wrapper(*args, **kwargs):
                print(' '*(self.indent * self.level) + '-' + fn.__name__)
                self.level += 1
                out = fn(*args, **kwargs)
                self.level -= 1
                return out
            return wrapper
    
    
    track = Tracker()
    
    @track
    def funct1():
        res = funct2()
        print(res)
    
    @track
    def funct2():
        factor = 3
        res = funct3(factor)
        return(res)
    
    @track
    def funct3(factor):
        res = 1 + 100*factor
        return(res)
    

    它使用类变量level 来跟踪调用了多少函数,并简单地打印出带有空格indent 的函数名称。所以调用funct1 给出:

    funct1()
    # prints:
    -funct1
      -funct2
        -funct3
    # returns:
    301
    

    根据您要保存输出的方式,您可以使用日志记录模块进行输出

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-22
      • 2023-03-14
      • 2011-06-19
      相关资源
      最近更新 更多