【问题标题】:How to trace a function call in Python?如何在 Python 中跟踪函数调用?
【发布时间】:2020-03-29 00:09:13
【问题描述】:

如何从头到尾跟踪 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)

所以这个“从头到尾的跟踪”看起来像这样:

  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. 第一行: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)

最后它返回消息“总和的结果是:5”

【问题讨论】:

  • 这叫做调试器。谷歌是你的朋友。而这个问题不属于 StackOverflow。它要求一个库/工具,这是明确禁止的。
  • 我知道调试是什么,但我想知道是否有更复杂的方法来进行这种“跟踪”

标签: python debugging tracking traceback ipdb


【解决方案1】:

您可以分析您的 Python 脚本。 Python 本身,在标准库中,有 [profilers] (https://docs.python.org/3/library/profile.html#introduction-to-the-profilers) 来分析和跟踪你的脚本。此外,还有一个名为 [Tuna] (https://github.com/nschloe/tuna) 的可视化库,可以帮助您以图形方式分析脚本。也许,您可以使用另一个工具来轻松跟踪您的整个脚本,称为 [KCacheGrind] (https://kcachegrind.github.io/html/Home.html),它显示了函数调用的可视化跟踪。

【讨论】:

  • 太好了,就是这样!谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-26
  • 2018-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多