Reputation: 2032
How do I print or show the recursive stack in Python when I'm running a recursive function?
Upvotes: 1
Views: 1697
Reputation: 4516
It's not clear what you want but as far as I get your question, you can print the stack of function callers in a recursive manner like the following, using the 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)
You can also use sys.get_frame()
to access the current frame and by using the f_locals
property, you can access the parameters passed to the current frame, in a recursive manner, you can observe this parameter decreasing.
Mostly all Information you want about the stack is also accessible from the frame objects that you can get as I've brought above.
Upvotes: 4