我找到了两种方法来做到这一点,都涉及到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