Print current call stack from a method in code


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

Asked By: oneself



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.

Answered By: RichieHindle
import traceback
Answered By: Mark Roddy

inspect.stack() returns the current stack rather than the exception traceback:

import inspect
print inspect.stack()

See for a log_stack utility function.

Answered By: Fred Loney

If you use python debugger, not only interactive probing of variables but you can get the call stack with the “where” command or “w”.

So at the top of your program

import pdb

Then in the code where you want to see what is happening


and you get dropped into a prompt

Answered By: Keir

Here’s a variation of @RichieHindle’s excellent answer which implements a decorator that can be selectively applied to functions as desired. Works with Python 2.7.14 and 3.6.4.

from __future__ import print_function
import functools
import traceback
import sys

INDENT = 4*' '

def stacktrace(func):
    def wrapped(*args, **kwds):
        # Get all but last line returned by traceback.format_stack()
        # which is the line below.
        callstack = 'n'.join([INDENT+line.strip() for line in traceback.format_stack()][:-1])
        print('{}() called:'.format(func.__name__))
        return func(*args, **kwds)

    return wrapped

def test_func():
    return 42


Output from sample:

test_func() called:
    File "", line 28, in <module>
Answered By: martineau

Install Inspect-it

pip3 install inspect-it --user


import inspect;print(*['{:40}| {}:{}n'.format(x.function, x.filename, x.lineno) for x in inspect.stack()])

you can Make a snippet of this line

it will show you a list of the function call stack with a filename and line number

list from start to where you put this line

Answered By: MohitGhodasara

for those who need to print the call stack while using pdb, just do

(Pdb) where
Answered By: mouserat
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.