打印 Python 堆栈跟踪,不引发异常

我的类的一个实例变量出了问题。我想让变量成为一个属性,无论何时访问它,我都想打印出所有代码的堆栈跟踪,这样我就可以看到它在哪里被篡改了。当没有引发异常时,如何打印堆栈跟踪?我知道如果有一个例外,我可以做一些像 traceback.format_tb(sys.exc_info()[2])

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

36080 次浏览

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

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.