views:

873

answers:

2

In Python, how can I print the current call stack from within a method (for debugging purposes).

+8  A: 

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 stdout, you can use:

traceback.print_stack()

but getting it via traceback.format_stack() lets you do whatever you like with it.

RichieHindle
+3  A: 
import traceback
traceback.print_stack()
Mark Roddy