gpt4 book ai didi

python - 在堆栈跟踪中打印函数的参数值

转载 作者:行者123 更新时间:2023-12-05 01:37:46 24 4
gpt4 key购买 nike

当打印错误堆栈跟踪时,我们如何在调用堆栈中打印传递给函数的参数值?我希望输出与下面的示例完全相同。

例子:

Traceback (most recent call last):
File "./file.py", line 615, in func0 **(arg0) arg0 = 0 was passed**
result = func1(arg1, arg2)
File "./file.py", line 728, in func1 **(arg1, arg2) arg1 = 1 and arg2 = 2 was passed**
return int_value[25]
TypeError: 'int' object is not iterable

除了堆栈跟踪中的正常输出之外,我还希望上面 ** ** 中的信息也被打印出来。我设想的是调试器也会自动打印传递的参数。这将清楚地显示数据通过的“功能管道”,管道中发生了什么,以及哪个功能没有做它应该做的事情。这将有助于调试很多。

我搜索了很多,发现了这些相关问题:

但它们的答案都不适合我:第一个答案导致 ModuleNotFoundError: No module named 'stackdump'。第二个问题的答案使我的 ipython 解释器崩溃,堆栈跟踪非常长。

我也查了一下:

TracebackException 似乎有一个capture_locals 变量,但我不太明白如何让它工作。

最佳答案

纯Python3

谈到 TracebackExceptions 和它的 capture_locals 参数,我们可以按如下方式使用它:

#!/usr/bin/env python3

import traceback

c = ['Help me!']

def bar(a = 3):
d = {1,2,3}
e = {}
foo(a)

def foo(a=4):
b = 4
if a != b:
raise Exception("a is not equal to 4")

try:
bar(3)
except Exception as ex:
tb = traceback.TracebackException.from_exception(ex, capture_locals=True)
print("".join(tb.format()))

打印每一帧的所有局部变量:

$ ./test.py 
Traceback (most recent call last):
File "./test.py", line 21, in <module>
bar(3)
__annotations__ = {}
__builtins__ = <module 'builtins' (built-in)>
__cached__ = None
__doc__ = None
__file__ = './test.py'
__loader__ = <_frozen_importlib_external.SourceFileLoader object at 0x7f81073704c0>
__name__ = '__main__'
__package__ = None
__spec__ = None
bar = <function bar at 0x7f81073b11f0>
c = ['Help me!']
ex = Exception('a is not equal to 4')
foo = <function foo at 0x7f810728a160>
traceback = <module 'traceback' from '/usr/lib/python3.8/traceback.py'>
File "./test.py", line 11, in bar
foo(a)
a = 3
d = {1, 2, 3}
e = {}
File "./test.py", line 17, in foo
raise Exception("a is not equal to 4")
a = 3
b = 4
Exception: a is not equal to 4

看起来有点过于冗长,但有时这些数据对于调试某些崩溃可能至关重要。

洛古鲁

还有一个包loguru打印“Fully descriptive exceptions”:

2018-07-17 01:38:43.975 | ERROR    | __main__:nested:10 - What?!
Traceback (most recent call last):

File "test.py", line 12, in <module>
nested(0)
└ <function nested at 0x7f5c755322f0>

> File "test.py", line 8, in nested
func(5, c)
│ └ 0
└ <function func at 0x7f5c79fc2e18>

File "test.py", line 4, in func
return a / b
│ └ 0
└ 5

ZeroDivisionError: division by zero

关于python - 在堆栈跟踪中打印函数的参数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60456113/

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