首页 如何在Jupyter中抑制回溯?

我找到了两种方法来做到这一点,都涉及到monkey补丁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
posted @ 2020-11-05 09:41  cup_leo  阅读(113)  评论(0编辑  收藏  举报