traceback.print_stack() using IPython's ultratb

雨燕双飞 提交于 2019-12-07 18:46:28

问题


For debugging/logging purposes, I would like to write the full stack to a file (such as in this question). I can do this using traceback.format_stack(). However, I would like it to look like the more verbose tracebacks that IPython outputs, for example, formatting with IPython.core.ultratb.VerboseTB.

It appears the classes and methods in IPython.core.ultratb require information on exceptions, as they are designed for tracebacks. But I have no exception: I just want to display the stack in a verbose way.

How can I use the output methods of IPython.core.ultratb.VerboseTB to format the stack such as reported by traceback.extract_stack() or inspect.stack()?


回答1:


import IPython.core.ultratb
import sys

try:
    1/0
except Exception as exc:
    tb = IPython.core.ultratb.VerboseTB()
    print(tb.text(*sys.exc_info()))

# --------------------------------------------------------------------------
# ZeroDivisionError                         Traceback (most recent call last)
# <ipython-input-8-725405cc4e58> in <module>()
#       1 try:
# ----> 2     1/0
#       3 except Exception as exc:
#       4     tb = IPython.core.ultratb.VerboseTB()
#       5     print(tb.text(*sys.exc_info()))
# 
# ZeroDivisionError: division by zero


来源:https://stackoverflow.com/questions/36088160/traceback-print-stack-using-ipythons-ultratb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!