In Python, how can I print the current call stack from within a method (for debugging purposes).
Advertisement
Answer
Here’s an example of getting the stack via the traceback module, and printing it:
JavaScript
x
19
19
1
import traceback
2
3
def f():
4
g()
5
6
def g():
7
for line in traceback.format_stack():
8
print(line.strip())
9
10
f()
11
12
# Prints:
13
# File "so-stack.py", line 10, in <module>
14
# f()
15
# File "so-stack.py", line 4, in f
16
# g()
17
# File "so-stack.py", line 7, in g
18
# for line in traceback.format_stack():
19
If you really only want to print the stack to stderr, you can use:
JavaScript
1
2
1
traceback.print_stack()
2
Or to print to stdout (useful if want to keep redirected output together), use:
JavaScript
1
2
1
traceback.print_stack(file=sys.stdout)
2
But getting it via traceback.format_stack()
lets you do whatever you like with it.