Print current call stack from a method in Python code
Here's an example of getting the stack via the traceback module, and printing it:
import tracebackdef 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:
Or to print to stdout (useful if want to keep redirected output together), use:
But getting it via
traceback.format_stack() lets you do whatever you like with it.