Jupyter Notebook 转存其他文件

nbconvert命令可以将jupyter的ipynb转为其他格式,或运行ipynb文件

命令行工具

运行nbconvert脚本的语法:

$ jupyter nbconvert --to FORMAT notebook.ipynb

将jupyter笔记本文件notebook.ipynb转为FORMAT字符串给出的格式。默认输出格式是html, --to可以省略

常用的支持输出格式:

  • HTML
  • LaTex
  • PDF
  • 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

PDF

  • --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)

参考

Python_Jupyter_自动执行jupyter

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值