从 Python 代码中的方法打印当前调用堆栈 [英] Print current call stack from a method in Python code
本文介绍了从 Python 代码中的方法打印当前调用堆栈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Python 中,如何从方法中打印当前调用堆栈(用于调试目的).
In Python, how can I print the current call stack from within a method (for debugging purposes).
推荐答案
这是通过 traceback 模块,并打印它:
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():
如果你真的只想把栈打印到stderr,你可以使用:
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)
但是通过 traceback.format_stack()
获取它可以让您随心所欲地使用它.
But getting it via traceback.format_stack()
lets you do whatever you like with it.
这篇关于从 Python 代码中的方法打印当前调用堆栈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文