打印 python 堆栈跟踪而不引发异常

发布于 2024-09-27 03:52:34 字数 223 浏览 1 评论 0原文

我的类的实例变量之一发生了一些问题。我想让该变量成为一个属性,每当访问它时,我都想打印出到该点的所有代码的堆栈跟踪,这样我就可以看到它在哪里被弄乱了。当没有引发异常时如何打印堆栈跟踪?我知道如果出现异常,我可以执行诸如 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 技术交流群。

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

发布评论

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

评论(2

枫以 2024-10-04 03:52:34

traceback.print_stack()

>>> def f():
...   def g():
...     traceback.print_stack()
...   g()
...
>>> f()
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in f
  File "<stdin>", line 3, in g

编辑:您还可以使用 extract_stack,取一个切片(例如 stack [5:] 用于排除前 5 个级别)并使用 format_list< /a> 获取可打印的堆栈跟踪 ('\n'.join(traceback.format_list(...)))

traceback.print_stack():

>>> def f():
...   def g():
...     traceback.print_stack()
...   g()
...
>>> f()
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in f
  File "<stdin>", line 3, in g

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

荒岛晴空 2024-10-04 03:52:34

如果您需要将字符串传递给记录器,您可以使用以下方法,而不是打印到标准输出:

''.join(traceback.format_stack())

请注意,traceback.format_stack() 将堆栈跟踪作为格式化字符串列表返回,因此您可以按照您想要的方式对其进行切片。要获取堆栈跟踪的最后几个元素,您可以执行以下操作:

''.join(traceback.format_stack()[-N:])

其中 N 是您感兴趣的级别数。

Instead of printing to stdout, if you need a string to pass to a logger you can use:

''.join(traceback.format_stack())

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:

''.join(traceback.format_stack()[-N:])

Where N is the number of levels you are interested in.

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