oneself oneself - 1 year ago 98
Python Question

Print current call stack from a method in Python code

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

Answer Source

Here's an example of getting the stack via the traceback module, and printing it:

import traceback

def f():

def g():
    for line in traceback.format_stack():


# Prints:
# File "", line 10, in <module>
#     f()
# File "", line 4, in f
#     g()
# File "", 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download