简体   繁体   中英

How do I suppress tracebacks in Jupyter?

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?

I have found a couple ways to do this, both involving monkeypatching IPython.

#1. This will output just the exception type and message but highlighted in red in the output area:

from __future__ import print_function  # for python 2 compatibility
import sys
ipython = get_ipython()

def exception_handler(exception_type, exception, traceback):
    print("%s: %s" % (exception_type.__name__, exception), file=sys.stderr)

ipython._showtraceback = exception_handler

#2. This will output the exception and color code the exception type (just like Jupyter normally does, but without the traceback):

import sys
ipython = get_ipython()

def hide_traceback(exc_tuple=None, filename=None, tb_offset=None,
                   exception_only=False, running_compiled_code=False):
    etype, value, tb = sys.exc_info()
    value.__cause__ = None  # suppress chained exceptions
    return ipython._showtraceback(etype, value, ipython.InteractiveTB.get_exception_only(etype, value))

ipython.showtraceback = hide_traceback

what about

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

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 Context

---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-188-8224aeca2117> in <module>
      1 get_ipython().run_line_magic('xmode', 'Context')
----> 2 x = 6/0

ZeroDivisionError: division by zero

xmode vErboSe

---------------------------------------------------------------------------
    ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-189-8fc1397d2e40> in <module>
      1 get_ipython().run_line_magic('xmode', 'Verbose')
----> 2 x = 6/0
        global x = ['a', 'b', 'c', 'd']

ZeroDivisionError: division by zero

I realize this question was asked a long time ago, but I expect others may land here and after searching stack exchange forever and never posting, I thought I would give back. I expect some etiquette flames. Be gentle and I will know better next time!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM