问题描述
我知道我可以打电话
jupyter nbconvert --execute --to html notebook.ipynb
来自 shell,或从 Python 进行系统调用:
import os
os.system('jupyter nbconvert --execute --to html notebook.ipynb')
但是当 nbconvert
模块在原生 Python 中可用时必须通过系统调用来执行此操作似乎很奇怪!
我想编写原生 python 来执行 iPython 笔记本并将其转换为 html 文件。 我稍微研究了 official documentation 但无法拼凑起来。 我的问题是:
- 是否有在原生 Python 中将笔记本转换为 html 的示例?
- 是否有令人信服的理由不这样做?
解决方法
好的,经过反复试验,我想通了:
import nbformat
from nbconvert.preprocessors import ExecutePreprocessor
from nbconvert import HTMLExporter
# read source notebook
with open('report.ipynb') as f:
nb = nbformat.read(f,as_version=4)
# execute notebook
ep = ExecutePreprocessor(timeout=-1,kernel_name='python3')
ep.preprocess(nb)
# export to html
html_exporter = HTMLExporter()
html_exporter.exclude_input = True
html_data,resources = html_exporter.from_notebook_node(nb)
# write to output file
with open("notebook.html","w") as f:
f.write(html_data)
诚然,比单个 os.system
调用要多得多,但我很惊讶那里的原生 Python 示例如此之少...