我有一些Jupyter笔记本,我想作为自动化测试运行。我可以通过运行jupyter nbconvert --execute Test.ipynb
从命令行执行此操作(有更好的方法吗?),如果任何Python单元格引发异常,它将引发异常。我也可以使用python API,它看起来像这样:
import nbformat
from nbconvert.preprocessors import ExecutePreprocessor
from nbconvert.preprocessors.execute import CellExecutionError
with open(notebook_filename, 'r') as f:
nb = nbformat.read(f, as_version=4)
ep = ExecutePreprocessor(kernel_name='python3')
try:
out = ep.preprocess(nb, {'metadata': {'path': './'}})
except CellExecutionError as e:
raise Exception('Python notebook %s failed with error: %s' % (notebook_filename, e))
但是,如果我的笔记本包含一个bash单元格,例如......
%%bash
python test.py
...如果在子进程中运行的python脚本引发了异常,则此异常不会显示在命令行中。可以肯定的是,该例外由笔记本注册并显示,例如
Traceback (most recent call last): File "test.py", line 1, in <module>
raise Exception('wat') Exception: wat
但是通过终端或python API调用它不会产生错误:
$ jupyter nbconvert --execute notebooks/Test.ipynb
[NbConvertApp] Converting notebook notebooks/Test.ipynb to html
[NbConvertApp] Executing notebook with kernel: python3
[NbConvertApp] Writing 249850 bytes to notebooks/Test.html
如何让Jupyter表现出这些错误?