具有参数值的Python打印调用堆栈

时间:2019-02-25 09:33:07

标签: python pdb

函数public class Startup { public Startup(IConfiguration configuration, IHostingEnvironment environment) { Configuration = configuration; Environment = environment; } public IConfiguration Configuration { get; } public IHostingEnvironment Environment { get; } public void ConfigureServices(IServiceCollection services) { services.AddMvc(); System.Console.WriteLine($"app: {environment.ApplicationName}"); } // rest omitted } 打印调用堆栈。如果我们可以在每个级别看到该参数的值,则将有助于调试。但是我找不到办法。

例如:

traceback.print_stack()

我想从PDB提示符下打印堆栈,以使其打印如下:

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

def f2(a=3):
  f3()

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

f1()

1 个答案:

答案 0 :(得分:1)

我写了一个模块,前段时间做了类似的事情。
我的笔记说它在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()