目录
nbconvert
命令可以将jupyter的ipynb
转为其他格式,或运行ipynb
文件
命令行工具
运行nbconvert
脚本的语法:
$ jupyter nbconvert --to FORMAT notebook.ipynb
将jupyter笔记本文件notebook.ipynb
转为FORMAT字符串给出的格式。默认输出格式是html
, --to
可以省略
常用的支持输出格式:
- HTML
- LaTex
- Markdown
- executable script
- notebook
HTML
--to html
--template full
: 默认,笔记本完整静态HTML渲染--template basic
: 简化的HTML--output <path>
: 指定输出文件--no-input
: 不保留代码
e.g.
$ jupyter nbconvert --to html test.ipynb
$ jupyter nbconvert --to html --template basic test.ipynb --output result/result.html
LaTex
--to latex
e.g.
$ jupyter nbconvert --to latex test.ipynb
--to pdf
: 通过LaTex生成PDF
e.g.
$ jupyter nbconvert --to pdf test.ipynb
Markdown
--to markdown
: markdown单元格不受影响,代码单元格缩进4个空格,图像以.png
文件形式输出到文件夹
e.g.
$ jupyter nbconvert --to markdown test.ipynb
Executable Script
--to script
: 将笔记本转为可执行脚本,注意:会略去魔法方法
e.g.
$ jupyter nbconvert --to script test.ipynb
Notebook
--to notebook
: 允许在笔记本上允许nbconvert
预处理器,或转为其他笔记本--execute
: 运行笔记本,结果保存到<filenam>.nbconvert.ipynb
--inplace
: 运行结果将覆盖输入文件,而不是写入新文件--allow-errors
: 运行期间单元格报错,不终止,继续运行后面的--output <path>
: 指定输出文件--ExecutePreprocessor.timeout
: 限定每个单元格超时时间,None或-1表示不限定
e.g.
$ jupyter nbconvert --to notebook --execute --inplate --allow-errors --ExecutePreprocessor.timeout=None --no-inpute test.ipynb --output result/test.ipynb
转换多个笔记本
方法1,命令行
$ jupyter nbconvert *.ipynb
$ jupyter nbconvert test1.ipynb test2.ipynb
方法2,配置mycfg.py
c = get_config()
c.NbConvertApp.notebooks = ["test1.ipynb", "test2.ipynb"]
$ jupyter nbconvert -- config myconfig.py
执行jupyter
方法1: 命令行
$ jupyter nbconvert --to notebook --execute test.ipynb
详情见[Notebook](# Notebook)
方法2: PythonAPI
import nbformat
from nbconvert.preprocessors import ExecutePreprocessor
# 加载notebook
with open("test.ipynb") as f:
nb = nbformat.read(f, as_version=6) # 指定版本
# 配置笔记本执行模式
# 设置单元格超时和执行内核,并在单元格报错后继续执行
ep = ExecutePreprocessor(timeout=600, kernel_name="python3", allow_errors=True)
# 运行
ep.preprocess(nb, {"metadata": {"path": "notebook/"}}) # path指定在那个文件夹中执行
# 保存
with open("result.ipynb", "w", encoding="utf8") as f:
nbformat.write(nb, f)