如何跟踪 Python 中的函数调用?

How to trace a function call in Python?

如何从头到尾跟踪 Python 代码?那展示了整个执行流程,从先调用哪个函数,执行了哪些操作,到整个流程结束。

看这个示例代码,它接收一个操作类型(加法或减法)和两个值(x和y),根据操作执行这两个值并在最后显示消息:

def calc(op, x, y):
    if op == 'sum':
        return x + y
    elif op == 'subtraction':
        return x - y


def msg(op, x, y):
    if op == 'sum':
        result = calc(op, x, y)
        return "The result of the sum is: " + str(result)
    elif op == 'subtraction':
        result = calc(op, x, y)
        return "The result of the subtraction is: " + str(result)


if __name__ == '__main__':
    my_sum = msg('sum', 3, 2)
    print(my_sum)

所以这个 "tracking from start to finish" 看起来像这样:

  1. 第 17 行:if __name__ == '__main__':
  2. 第 18 行:my_sum = msg('sum', 3, 2)
  3. 第 8 行:def msg(op, x, y):
  4. 第 9 行:if op == 'sum':
  5. 第 10 行:result = calc(op, x, y)
  6. 第 1 行:def calc(op, x, y):
  7. 第 2 行:if op == 'sum':
  8. 第 3 行:return x + y
  9. 第 11 行:return "The result of the sum is:" + str(result)
  10. 第 19 行:print(my_sum)

最后 returns 消息 "The result of the sum is: 5".

您可以分析您的 Python 脚本。 Python 本身,在标准库中,有 [分析器] (https://docs.python.org/3/library/profile.html#introduction-to-the-profilers) to profile and trace your script. Also, there are a visual library called [Tuna] (https://github.com/nschloe/tuna) that can help you to graphically profile your script. Maybe, you can use another tool, to easy trace your entire script, called [KCacheGrind] (https://kcachegrind.github.io/html/Home.html),它显示了函数调用的视觉导向跟踪。