这是一个代码,用于捕获在执行 nbconvert 期间产生的警告和异常并将它们传递给记录器。Jupyter 和 nbconvert 使用不同的方式处理异常。
from logging import getLogger
import sys
import traceback
import warnings
import IPython
import logging
logger = getLogger(name)
logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
# Catch Traceback
def showtraceback(self):
traceback_lines = traceback.format_exception(*sys.exc_info())
del traceback_lines[1]
message = ''.join(traceback_lines)
logger.error(traceback_lines[-1] + str(message))
IPython.core.interactiveshell.InteractiveShell.showtraceback = showtraceback
# Catch Warning
def warning_on_one_line(message, category, filename, lineno, file=None, line=None):
logger.warning(str(message) + '\n' + str(filename) + ' : ' + str(lineno))
return '%s:%s: %s:%s\n' % (filename, lineno, category.__name__, message)
warnings.formatwarning = warning_on_one_line