将 Jupyter Notebook 转换为原生 Python 中的 html 输出

GZ-*_*GZ- 1 jupyter jupyter-notebook nbconvert

我知道我可以打电话

jupyter nbconvert --execute --to html notebook.ipynb
Run Code Online (Sandbox Code Playgroud)

从 shell,或者从 Python 进行系统调用:

import os
os.system('jupyter nbconvert --execute --to html notebook.ipynb')
Run Code Online (Sandbox Code Playgroud)

nbconvert但是,当本机 Python 中存在可用模块时,必须通过系统调用来执行此操作似乎很奇怪!

我想编写本机 python 来执行 iPython 笔记本并将其转换为 html 文件。我研究了一些官方文档,但无法将它们拼凑起来。我的问题是:

  1. 是否有一个在本机 Python 中将笔记本转换为 html 的示例?
  2. 有令人信服的理由不这样做吗?

GZ-*_*GZ- 7

好吧,经过一番尝试和错误后我发现:

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)
Run Code Online (Sandbox Code Playgroud)

诚然,这比一次调用要多做很多工作os.system,但令我惊讶的是,原生 Python 示例如此之少……