gpt4 book ai didi

python - 如何在Python中打印递归堆栈

转载 作者:行者123 更新时间:2023-11-30 22:50:14 25 4
gpt4 key购买 nike

当我运行递归函数时,如何在 Python 中打印或显示递归堆栈?

最佳答案

尚不清楚你想要什么,但据我得到你的问题,你可以使用 python inspect module 以递归方式打印函数调用者堆栈,如下所示.

import inspect, sys

max_recursion_depth = 10

def rec_func(recursion_index):
if recursion_index == 0:
return

rec_func(recursion_index-1)

current_frame = inspect.currentframe()
calframe = inspect.getouterframes(current_frame, 2)

frame_object = calframe[0][0]

print("Recursion-%d: %s" % (max_recursion_depth - recursion_index, frame_object.f_locals))
print("Passed parameters: %s" % (sys._getframe(1).f_locals) )


rec_func(max_recursion_depth)

您还可以使用sys.get_frame()来访问当前帧,并通过使用f_locals属性,您可以访问传递给当前帧的参数,在通过递归方式,您可以观察到该参数逐渐减小。

大多数情况下,您想要的有关堆栈的所有信息也可以从我上面提到的框架对象中访问。

关于python - 如何在Python中打印递归堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39464057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com