How do I suppress tracebacks in Jupyter?

Viewed 3270

I want to hide tracebacks in my Python code in Jupyter notebooks, so only the error type and message are displayed.

This answer suggests sys.tracebacklimit = 0 but trying that gave the following:

ERROR:root:Internal Python error in the inspect module.
Below is the traceback from this internal error.

ERROR:root:Internal Python error in the inspect module.
Below is the traceback from this internal error.

Traceback (most recent call last): 
AssertionError 
Traceback (most recent call last): 
AssertionError

That answer also suggests replacing sys.excepthook with a custom function, but the traceback was still displayed.

How can I hide the traceback?

3 Answers

I think the xmode magic is what you are looking for here. Just type it in a cell. There are four modes: Context, Minimal, Verbose and Plain(the default I think). you can either use xmode <mode> or with no argument it toggles to the next mode.

In [1]: %xmode
Exception reporting mode: Minimal

In [2]: %xmode
Exception reporting mode: Plain

Here is the difference with a simple error. It becomes easier to see the differences with more detailed error messages.

xmode Minimal

x = 6 / 0

returns

ZeroDivisionError: division by zero

xmode plain

x = 6 / 0


Traceback (most recent call last):
                                                                        
File "<ipython-input-187-28f66aec0cca>", line 2, in <module>
x = 6/0

ZeroDivisionError: division by zero




%xmode Plain
<PRE>pd.read_csv("foo.bar")
%xmode Context
pd.read_csv("foo.bar")
%xmode Verbose
pd.read_csv("foo.bar")


         

what about

import functools
ipython = get_ipython()
method_name = "showtraceback"
setattr(
    ipython,
    method_name,
    functools.partial(
        getattr(ipython, method_name),
        exception_only=True
    )
)
Related