在原生 Python 中将 Jupyter 笔记本转换为 html 输出

问题描述

我知道我可以打电话

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 但无法拼凑起来。 我的问题是:

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

解决方法

好的,经过反复试验,我想通了:

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 示例如此之少...

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...