在Python中,如何从方法中打印当前调用堆栈(用于调试目的)。
当前回答
下面是@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
其他回答
如果您使用python调试器,不仅可以交互式探测变量,还可以使用“where”命令或“w”获取调用堆栈。
在程序的顶部
import pdb
然后在代码中查看发生了什么
pdb.set_trace()
然后你就进入了提示符
Inspect.stack()返回当前堆栈,而不是异常回溯:
import inspect
print inspect.stack()
有关log_stack实用函数,请参阅https://gist.github.com/FredLoney/5454553。
import traceback
traceback.print_stack()
下面是@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
Code
import inspect;print(*['{:40}| {}:{}\n'.format(x.function, x.filename, x.lineno) for x in inspect.stack()])
你可以对这一行做一个代码片段
它将向您显示带有文件名和行号的函数调用堆栈列表
列出从开始到放这一行的位置
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录