gpt4 book ai didi

python - 如何使用参数值打印调用堆栈?

转载 作者:行者123 更新时间:2023-12-05 05:12:08 26 4
gpt4 key购买 nike

函数 traceback.print_stack() 打印调用堆栈。如果我们可以看到每个级别的参数值,它将有助于调试。但是我找不到办法做到这一点。

例如:

def f1(a=2):
f2(a=a+1)

def f2(a=3):
f3()

def f3(a=4):
print(a)
pdb.set_trace()

f1()

我想从 PDB 提示符中打印堆栈,以便打印如下:

f3 a = Not specified
f2 a = 3
f1

最佳答案

我刚才写了一个模块来做类似的事情。
我的笔记说它适用于 Python 2 和 3。

from __future__ import print_function
from itertools import chain
import traceback
import sys

def stackdump(id='', msg='HERE'):
print('ENTERING STACK_DUMP' + (': '+id) if id else '')
raw_tb = traceback.extract_stack()
entries = traceback.format_list(raw_tb)

# Remove the last two entries for the call to extract_stack() and to
# the one before that, this function. Each entry consists of single
# string with consisting of two lines, the script file path then the
# line of source code making the call to this function.
del entries[-2:]

# Split the stack entries on line boundaries.
lines = list(chain.from_iterable(line.splitlines() for line in entries))
if msg: # Append it to last line with name of caller function.
lines[-1] += ' <-- ' + msg
lines.append('LEAVING STACK_DUMP' + (': '+id) if id else '')
print('\n'.join(lines))
print()

sys.modules[__name__] = stackdump # Make a callable module.


if __name__ == '__main__':

import stackdump

def func1():
stackdump('A')

def func2():
func1()

func1()
print()
func2()

关于python - 如何使用参数值打印调用堆栈?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54863123/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com