我想在Jupyter笔记本中隐藏我的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
,但仍会显示回溯。
如何隐藏追溯?
答案 0 :(得分:5)
我找到了几种方法,都涉及monkeypatching 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()
return ipython._showtraceback(etype, value, ipython.InteractiveTB.get_exception_only(etype, value))
ipython.showtraceback = hide_traceback
答案 1 :(得分:0)
关于
import functools
ipython = get_ipython()
method_name = "showtraceback"
setattr(
ipython,
method_name,
functools.partial(
getattr(ipython, method_name),
exception_only=True
)
)