traceback.print_stack() using IPython's ultratb
Asked Answered
K

1

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

Kilohertz answered 18/3, 2016 at 15:22 Comment(3)
try something like ltratb.VerboseTB()(etb=traceback.extract_stack())Flavescent
@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.Kilohertz
See also this related question. E.g. the py_better_exchook library can do that, via its print_tb (disclaimer: I wrote that).Retortion
S
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
Stringboard answered 21/3, 2018 at 15:49 Comment(2)
Note that this will give you the stack of the exception only, not the full stack.Retortion
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.Jeffreyjeffreys

© 2022 - 2024 — McMap. All rights reserved.