In Python, how can I print the current call stack from within a method (for debugging purposes).
If you use python debugger, not only interactive probing of variables but you can get the call stack with the "where" command or "w".
The Python interpreter uses a call stack to run a Python program. When a function is called in Python, a new frame is pushed onto the call stack for its local execution, and every time a function call returns, its frame is popped off the call stack.
Description. By default traceback() prints the call stack of the last uncaught error, i.e., the sequence of calls that lead to the error. This is useful when an error occurs with an unidentifiable error message. It can also be used to print the current stack or arbitrary lists of calls.
Here's an example of getting the stack via the traceback module, and printing it:
import traceback def f(): g() def g(): for line in traceback.format_stack(): print(line.strip()) f() # Prints: # File "so-stack.py", line 10, in <module> # f() # File "so-stack.py", line 4, in f # g() # File "so-stack.py", line 7, in g # for line in traceback.format_stack():
If you really only want to print the stack to stderr, you can use:
traceback.print_stack()
Or to print to stdout (useful if want to keep redirected output together), use:
traceback.print_stack(file=sys.stdout)
But getting it via traceback.format_stack()
lets you do whatever you like with it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With