代码之家  ›  专栏  ›  技术社区  ›  oneself

从python代码中的方法打印当前调用堆栈

  •  220
  • oneself  · 技术社区  · 15 年前

    在python中,如何从方法中打印当前调用堆栈(用于调试)。

    5 回复  |  直到 7 年前
        1
  •  250
  •   Quentin Pradet    9 年前

    下面是一个通过 traceback 模块,并打印:

    import traceback
    
    def f():
        g()
    
    def g():
        for line in traceback.format_stack():
            print(line.strip())
    
    f()
    
    # Prints:
    # File "so-stack.py", line 10, in <module>
    #     f()
    # File "so-stack.py", line 4, in f
    #     g()
    # File "so-stack.py", line 7, in g
    #     for line in traceback.format_stack():
    

    如果只想将堆栈打印到stderr,可以使用:

    traceback.print_stack()
    

    或者,要打印到stdout(如果希望将重定向的输出保持在一起,则很有用),请使用:

    traceback.print_stack(file=sys.stdout)
    

    但通过 traceback.format_stack() 让你用它做你喜欢做的任何事。

        2
  •  77
  •   Mark Roddy    15 年前
    import traceback
    traceback.print_stack()
    
        3
  •  27
  •   Fred Loney    11 年前

    inspect.stack() 返回当前堆栈而不是异常回溯:

    import inspect
    print inspect.stack()
    

    https://gist.github.com/FredLoney/5454553 对于日志堆栈实用程序函数。

        4
  •  9
  •   Keir    8 年前

    如果使用python调试器,不仅可以交互式地探测变量,还可以使用“where”命令或“w”获取调用堆栈。

    所以在你的计划的顶端

    import pdb
    

    然后在代码中你想看到发生了什么

    pdb.set_trace()
    

    然后你就会被提示

        5
  •  0
  •   martineau    7 年前

    下面是@richiehindle的优秀答案的变体,它实现了一个装饰器,可以根据需要选择性地应用到函数中。适用于python 2.7.14和3.6.4。

    from __future__ import print_function
    import functools
    import traceback
    import sys
    
    INDENT = 4*' '
    
    def stacktrace(func):
        @functools.wraps(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__))
            print(callstack)
            return func(*args, **kwds)
    
        return wrapped
    
    @stacktrace
    def test_func():
        return 42
    
    print(test_func())
    

    样本输出:

    test_func() called:
        File "stacktrace_decorator.py", line 28, in <module>
        print(test_func())
    42