6

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

azmeuk
  • 4,026
  • 3
  • 37
  • 64
gerrit
  • 24,025
  • 17
  • 97
  • 170
  • try something like ```ltratb.VerboseTB()(etb=traceback.extract_stack())``` – mingaleg Mar 18 '16 at 18:42
  • @shhdup that gives `AttributeError: 'StackSummary' object has no attribute 'tb_frame'` (in `inspect.getinnerframes`) *and* `TypeError: 'NoneType' object is not iterable` (in `ultratb.VerboseTB.format_records`). I'm not sure why I get two exceptions (with tracebacks) for a single expression, but I do. – gerrit Mar 18 '16 at 18:51
  • 2
    See also [this related question](https://stackoverflow.com/questions/1308607/python-assert-improved-introspection-of-failure). E.g. the [py_better_exchook library](https://github.com/albertz/py_better_exchook/) can do that, via its `print_tb` (disclaimer: I wrote that). – Albert Oct 07 '18 at 12:45

1 Answers1

2
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
gerrit
  • 24,025
  • 17
  • 97
  • 170
azmeuk
  • 4,026
  • 3
  • 37
  • 64
  • 2
    Note that this will give you the stack of the exception only, not the full stack. – Albert Oct 07 '18 at 12:46
  • This does not answer the question. It is specified that a full traceback is desired regardless of exception. Besides, even if you add code inside the try block you will only get a traceback for the divide by zero exception. – Sherman Mar 11 '22 at 01:49