从Python代码中的方法打印当前调用堆栈 [英] Print current call stack from a method in Python code

查看:1499
本文介绍了从Python代码中的方法打印当前调用堆栈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

通过追溯模块获取堆栈的示例,然后打印:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆