Стек вызовов печати Python со значениями аргументов - PullRequest
0 голосов
/ 25 февраля 2019

Функция traceback.print_stack() печатает стек вызовов.Если бы мы могли видеть значения аргумента на каждом уровне, это помогло бы отладить.Но я не смог найти способ сделать это.

Например:

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

def f2(a=3):
  f3()

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

f1()

Я хочу напечатать стек из приглашения PDB, чтобы он печатал как:

  f3 a = Not specified
  f2 a = 3
  f1 

1 Ответ

0 голосов
/ 25 февраля 2019

Я написал модуль, который делает нечто подобное некоторое время назад.Мои заметки говорят, что это работает как в Python 2, так и в 3.

from __future__ import print_function
from itertools import chain
import traceback

def stackdump(msg='HERE'):
    print('  ENTERING STACK_DUMP()')
    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()')
    print('\n'.join(lines))


if __name__ == '__main__':

    def func1():
        stackdump()

    def func2():
        func1()

    func1()
    print()
    func2()
...