如何打印出已经返回的函数调用的堆栈跟踪?

2024-06-16 11:16:04 发布

您现在位置:Python中文网/ 问答频道 /正文

例如:

with magically_trace_stack() as trace:
    func(1, 2)
print(trace.format_tb())

func可以调用几十个其他函数,我想知道是哪个函数。你知道吗

(附言:不要给我推荐一个调试器)

扩展示例

def b():
    print('b')

def a():
    print('a')
    b()

def func():
    print('func')
    a()

with magically_trace_stack() as trace:
    func()
trace.print_stack()

打印的堆栈应该是这样的:

called func
called a
called b
exit b
exit a
exit func

函数ab是隐藏的,我只能访问func。你知道吗


Tags: 函数formatstackdefaswithexittrace
1条回答
网友
1楼 · 发布于 2024-06-16 11:16:04

您可以创建一个上下文管理器类,该类使用^{}启用解释器的跟踪函数,方法是将跟踪事件和帧附加到列表中:

import sys

class magically_trace_stack:
    def __init__(self):
        self.events = []

    def __enter__(self):
        sys.settrace(self.trace)
        return self

    def __exit__(self, *args):
        sys.settrace(None)

    def trace(self, frame, event, arg):
        # we don't want to record the call to the exit of the context manager
        if frame.f_code is not self.__exit__.__func__.__code__:
            self.events.append((frame, event, arg))
        return self.trace

    def print_stack(self):
        for frame, event, arg in self.events:
            if event == 'call':
                print(f'called {frame.f_code.co_name}')
            elif event == 'return':
                print(f'exit {frame.f_code.co_name} with {arg}')

以便:

def b():
    print('b')
    return 1

def a():
    print('a')
    b()
    return 2

def func():
    print('func')
    a()

with magically_trace_stack() as trace:
    func()
trace.print_stack()

输出:

func
a
b
called func
called a
called b
exit b with 1
exit a with 2
exit func with None

相关问题 更多 >