从代码中的方法打印当前调用堆栈

发布于 2024-07-27 13:55:30 字数 42 浏览 6 评论 0原文

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

灯下孤影 2024-08-03 13:55:31

inspect.stack() 返回当前堆栈而不是异常回溯:

import inspect
print inspect.stack()

请参阅 https: //gist.github.com/FredLoney/5454553 用于 log_stack 实用函数。

inspect.stack() returns the current stack rather than the exception traceback:

import inspect
print inspect.stack()

See https://gist.github.com/FredLoney/5454553 for a log_stack utility function.

终陌 2024-08-03 13:55:31

如果您使用Python调试器,不仅可以交互式探测变量,还可以使用“where”命令或“w”获取调用堆栈。

因此,在程序的顶部

import pdb

,然后在您想要查看正在发生的情况的代码中

pdb.set_trace()

,您会进入提示符

If you use python debugger, not only interactive probing of variables but you can get the call stack with the "where" command or "w".

So at the top of your program

import pdb

Then in the code where you want to see what is happening

pdb.set_trace()

and you get dropped into a prompt

妖妓 2024-08-03 13:55:31

这是 @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

Here's a variation of @RichieHindle's excellent answer which implements a decorator that can be selectively applied to functions as desired. Works with Python 2.7.14 and 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())

Output from sample:

test_func() called:
    File "stacktrace_decorator.py", line 28, in <module>
    print(test_func())
42
時窥 2024-08-03 13:55:31

安装Inspect-it

pip3 install inspect-it --user

代码

import inspect
print(*['{:40}| {}:{}\n'.format(x.function, x.filename, x.lineno) 
        for x in inspect.stack()])

您可以制作此行的片段

它将向您显示函数调用堆栈的列表

从开始到放置此行的位置的列表

Install Inspect-it

pip3 install inspect-it --user

Code

import inspect
print(*['{:40}| {}:{}\n'.format(x.function, x.filename, x.lineno) 
        for x in inspect.stack()])

you can Make a snippet of this line

it will show you a list of the function call stack with a filename and line number

list from start to where you put this line

萧瑟寒风 2024-08-03 13:55:31

使用 walk_stack 方法返回当前堆栈中存储的历史记录(None):

import traceback
for trace, _ in traceback.walk_stack(None):
    print(trace)
    print(trace.f_locals)

Use walk_stack method to return to the history stored in the current stack (None):

import traceback
for trace, _ in traceback.walk_stack(None):
    print(trace)
    print(trace.f_locals)
嘦怹 2024-08-03 13:55:30

这是通过 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()

或者打印到 stdout(如果想将重定向输出保持在一起很有用),使用:

traceback.print_stack(file=sys.stdout)

但是通过 traceback.format_stack() 获取它可以让您做到无论你喜欢什么。

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():

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)

But getting it via traceback.format_stack() lets you do whatever you like with it.

半夏半凉 2024-08-03 13:55:30
import traceback
traceback.print_stack()
import traceback
traceback.print_stack()
尤怨 2024-08-03 13:55:30

对于那些需要在使用 pdb 时打印调用堆栈的人,只需这样做

(Pdb) where

for those who need to print the call stack while using pdb, just do

(Pdb) where
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文