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

问题:从Python代码中的方法打印当前调用堆栈

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

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


回答 0

这是通过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()

或打印到标准输出(如果要一起保留重定向输出很有用),请使用:

traceback.print_stack(file=sys.stdout)

但是通过获取它可以traceback.format_stack()让您随心所欲地使用它。

Here’s an example of getting the stack via the traceback module, and printing it:

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():

If you really only want to print the stack to stderr, you can use:

traceback.print_stack()

Or to print to stdout (useful if want to keep redirected output together), use:

traceback.print_stack(file=sys.stdout)

But getting it via traceback.format_stack() lets you do whatever you like with it.


回答 1

import traceback
traceback.print_stack()
import traceback
traceback.print_stack()

回答 2

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

import inspect
print inspect.stack()

请参阅https://gist.github.com/FredLoney/5454553以获取log_stack实用程序功能。

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

import inspect
print inspect.stack()

See https://gist.github.com/FredLoney/5454553 for a log_stack utility function.


回答 3

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

因此,在程序顶部

import pdb

然后在代码中您要查看发生了什么

pdb.set_trace()

并提示您

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

pdb.set_trace()

and you get dropped into a prompt


回答 4

对于那些在使用pdb时需要打印调用堆栈的用户,只需执行

(Pdb) where

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

(Pdb) where

回答 5

这是@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

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):
    @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())

Output from sample:

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

回答 6

安装检查

pip3 install inspect-it --user

import inspect;print(*['\n\x1b[0;36;1m| \x1b[0;32;1m{:25}\x1b[0;36;1m| \x1b[0;35;1m{}'.format(str(x.function), x.filename+'\x1b[0;31;1m:'+str(x.lineno)+'\x1b[0m') for x in inspect.stack()])

你可以做这行的片段

它会向您显示函数调用堆栈的列表,其中包含文件名和行号

从头到尾放置此行的列表

Install Inspect-it

pip3 install inspect-it --user

Code

import inspect;print(*['\n\x1b[0;36;1m| \x1b[0;32;1m{:25}\x1b[0;36;1m| \x1b[0;35;1m{}'.format(str(x.function), x.filename+'\x1b[0;31;1m:'+str(x.lineno)+'\x1b[0m') 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