在 Python 中,如何从方法中打印当前调用堆栈(用于调试目的)。
这是通过 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()
获取它可以让你用它做任何你喜欢的事情。
import traceback
traceback.print_stack()
对于那些需要在使用 pdb 时打印调用堆栈的人,只需这样做
(Pdb) where
inspect.stack()
返回当前堆栈而不是异常回溯:
import inspect
print inspect.stack()
请参阅 https://gist.github.com/FredLoney/5454553 了解 log_stack 实用函数。
如果您使用Python调试器,不仅可以交互式探测变量,还可以使用“where”命令或“w”获取调用堆栈。
所以在你的程序的顶部
import pdb
然后在你想查看发生了什么的代码中
pdb.set_trace()
然后你会进入提示
这是 @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
安装检查
pip3 install inspect-it --user
代码
import inspect;print(*['{:40}| {}:{}\n'.format(x.function, x.filename, x.lineno) for x in inspect.stack()])
您可以制作此行的片段
它将向您显示函数调用堆栈的列表,其中包含文件名和行号
从开始到放置此行的位置列出
使用
walk_stack
方法返回当前堆栈中存储的历史记录(None
):
import traceback
for trace, _ in traceback.walk_stack(None):
print(trace)
print(trace.f_locals)