Ric*_*dle 294
这是通过回溯模块获取堆栈并打印它的示例:
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():
Run Code Online (Sandbox Code Playgroud)
如果你真的只想将堆栈打印到stderr,你可以使用:
traceback.print_stack()
Run Code Online (Sandbox Code Playgroud)
或者要打印到stdout(如果想要将重定向的输出保持在一起很有用),请使用:
traceback.print_stack(file=sys.stdout)
Run Code Online (Sandbox Code Playgroud)
但通过它可以traceback.format_stack()
让你做任何你喜欢的事情.
Mar*_*ddy 89
import traceback
traceback.print_stack()
Run Code Online (Sandbox Code Playgroud)
Fre*_*ney 40
inspect.stack()
返回当前堆栈而不是异常回溯:
import inspect
print inspect.stack()
Run Code Online (Sandbox Code Playgroud)
有关log_stack实用程序功能,请参阅https://gist.github.com/FredLoney/5454553.
Kei*_*eir 14
如果使用python调试器,不仅可以交互式探测变量,还可以使用"where"命令或"w"获取调用堆栈.
所以在你的程序的顶部
import pdb
Run Code Online (Sandbox Code Playgroud)
然后在代码中你想看到发生了什么
pdb.set_trace()
Run Code Online (Sandbox Code Playgroud)
然后你就会陷入提示
这是 @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())
Run Code Online (Sandbox Code Playgroud)
样本输出:
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())
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
114529 次 |
最近记录: |