打印python堆栈跟踪无一例外地被提出 [英] print python stack trace without exception being raised

查看:151
本文介绍了打印python堆栈跟踪无一例外地被提出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一个类的实例变量发生了一些事情。我想使变量成为一个属性,每当访问时,我想打印出所有代码的堆栈跟踪,直到这一点,所以我可以看到它被弄乱了。当没有异常提出时,如何打印出堆栈跟踪?我知道如果有一个例外,我可以做一些例如 traceback.format_tb(sys.exc_info()[2])



也可能有用的只是打印最后3-4个级别,因为前几个可能不会那么有趣。

解决方案

traceback.print_stack()

 >>> def f():
... def g():
... traceback.print_stack()
... g()
...
>>> f()
文件< stdin>,第1行,< module>
文件< stdin>,第4行,f
文件< stdin>,第3行,g

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


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.

解决方案

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

这篇关于打印python堆栈跟踪无一例外地被提出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆