如何在 Jupyter 中抑制回溯?

How do I suppress tracebacks in Jupyter?

我想在 Jupyter notebooks 的 Python 代码中隐藏回溯,因此只显示错误类型和消息。

This answer 建议 sys.tracebacklimit = 0 但尝试给出以下结果:

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

该答案还建议用自定义函数替换 sys.excepthook,但回溯仍然显示。

如何隐藏回溯?

我找到了几种方法来做到这一点,都涉及猴子修补 IPython。

#1。这将只输出异常类型和消息,但在输出区域中以红色突出显示:

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。这将输出异常和异常类型的颜色代码(就像 Jupyter 通常那样,但没有回溯):

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

怎么样

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

我认为 xmode 魔法正是您在这里寻找的。只需在单元格中输入即可。有四种模式:Context、Minimal、Verbose 和 Plain(我认为是默认模式)。您可以使用 xmode <mode> 或不带参数切换到下一个模式。

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

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

这是一个简单错误的区别。更详细的错误消息更容易看出差异。

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")