Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print call stack with argument values?

Tags:

python

pdb

The function traceback.print_stack() prints the call stack. If we could see the values of the argument at each level, it would help debug. But I could not find a way to do this.

For example:

def f1(a=2):
  f2(a=a+1)

def f2(a=3):
  f3()

def f3(a=4):
  print(a)
  pdb.set_trace()

f1()

I want to print the stack from the PDB prompt so that it prints like:

f3 a = Not specified
f2 a = 3
f1
like image 693
Suresh Avatar asked Dec 08 '25 10:12

Suresh


1 Answers

I wrote a module that does something like this a while ago.
My notes say it works in both Python 2 and 3.

from __future__ import print_function
from itertools import chain
import traceback
import sys

def stackdump(id='', msg='HERE'):
    print('ENTERING STACK_DUMP' + (': '+id) if id else '')
    raw_tb = traceback.extract_stack()
    entries = traceback.format_list(raw_tb)

    # Remove the last two entries for the call to extract_stack() and to
    # the one before that, this function. Each entry consists of single
    # string with consisting of two lines, the script file path then the
    # line of source code making the call to this function.
    del entries[-2:]

    # Split the stack entries on line boundaries.
    lines = list(chain.from_iterable(line.splitlines() for line in entries))
    if msg:  # Append it to last line with name of caller function.
        lines[-1] += ' <-- ' + msg
        lines.append('LEAVING STACK_DUMP' + (': '+id) if id else '')
    print('\n'.join(lines))
    print()

sys.modules[__name__] = stackdump  # Make a callable module.


if __name__ == '__main__':

    import stackdump

    def func1():
        stackdump('A')

    def func2():
        func1()

    func1()
    print()
    func2()
like image 71
martineau Avatar answered Dec 10 '25 00:12

martineau