打印python堆栈跟踪无一例外地被引发
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3925248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
print python stack trace without exception being raised
提问by Claudiu
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]).
我的班级的一个实例变量发生了一些事情。我想让变量成为一个属性,每当它被访问时,我想打印出导致该点的所有代码的堆栈跟踪,这样我就可以看到它被弄乱的地方。当没有引发异常时如何打印堆栈跟踪?我知道如果有例外我可以做类似的事情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.
另外可能有用的是仅打印最后 3-4 个级别,因为前几个级别可能不会那么有趣。
采纳答案by Claudiu
>>> 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_listto get a print-ready stacktrace ('\n'.join(traceback.format_list(...)))
编辑:您还可以使用extract_stack,取一个切片(例如stack[5:]排除前 5 个级别)并使用format_list来获取可打印的堆栈跟踪( '\n'.join(traceback.format_list(...)))
回答by rouble
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:
请注意, traceback.format_stack() 将堆栈跟踪作为格式化的字符串列表返回,因此您可以随意对其进行切片。要获取堆栈跟踪的最后几个元素,您可以执行以下操作:
''.join(traceback.format_stack()[-N:])
Where N is the number of levels you are interested in.
其中 N 是您感兴趣的级别数。

