打印 python 堆栈跟踪而不引发异常
我的类的实例变量之一发生了一些问题。我想让该变量成为一个属性,每当访问它时,我都想打印出到该点的所有代码的堆栈跟踪,这样我就可以看到它在哪里被弄乱了。当没有引发异常时如何打印堆栈跟踪?我知道如果出现异常,我可以执行诸如 traceback.format_tb(sys.exc_info()[2])
之类的操作。
另外,可能有用的是仅打印最后 3-4 个级别,因为前几个级别可能不会那么有趣。
Something is happening with one of my class's instance variables. I want to make the variable a property, and whenever it is accessed I want to print out the stack trace of all the code leading up to that point, so I can see where it's being messed with. How do I print out the stack trace when no exception has been raised? I know if there is an exception I can do something like traceback.format_tb(sys.exc_info()[2])
.
Also what might be useful is to print only the last 3-4 levels, since the first few are probably not going to be that interesting.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
traceback.print_stack()
:编辑:您还可以使用 extract_stack,取一个切片(例如
stack [5:]
用于排除前 5 个级别)并使用 format_list< /a> 获取可打印的堆栈跟踪 ('\n'.join(traceback.format_list(...))
)traceback.print_stack()
:Edit: You can also use extract_stack, take a slice (e.g.
stack[5:]
for exclude the first 5 levels) and use format_list to get a print-ready stacktrace ('\n'.join(traceback.format_list(...))
)如果您需要将字符串传递给记录器,您可以使用以下方法,而不是打印到标准输出:
请注意,traceback.format_stack() 将堆栈跟踪作为格式化字符串列表返回,因此您可以按照您想要的方式对其进行切片。要获取堆栈跟踪的最后几个元素,您可以执行以下操作:
其中 N 是您感兴趣的级别数。
Instead of printing to stdout, if you need a string to pass to a logger you can use:
Note, that traceback.format_stack() returns the stacktrace as a formatted list of strings, so you can slice it anyway you want. To get the last few elements of the stacktrace you could do:
Where N is the number of levels you are interested in.