首页 > 解决方案 > 在 Jupyter Notebook 中隐藏代码单元,使用 Papermill 执行,使用 nbconvert 转换为 PDF

问题描述

我想运行一个python程序(不是命令行)papermill来执行jupyter笔记本,然后将其转换为 PDF。这个想法很有效,但我无法隐藏输入单元格。

For应该隐藏输入单元格,但Classicpapermill report_mode = True似乎存在问题( https://github.com/nteract/papermill/issues/130jupyter

hide_input 或 html 脚本等其他扩展也不够用。也许nbconvert隐藏单元格的模板是一个解决方案,但我没有让它运行。

我的最小代码:

pm.execute_notebook(
        "Input.ipynb",
        "Output.ipynb",
        parameters=dict(id=id),
        report_mode=True,
    )
notebook_filename = "Output.ipynb"

with open(notebook_filename) as f:
    nb = nbformat.read(f, as_version=4)
pdf_exporter = PDFExporter()
pdf_data, resources = pdf_exporter.from_notebook_node(nb)

所以我正在寻找一种方法来执行笔记本,隐藏输入单元格并将笔记本转换为 PDF。我想使用nbconvertinPython而不是作为命令行工具,因为脚本应该每天运行。

标签: python-3.xjupyter-notebooknbconvertpapermill

解决方案


我知道您说您“不想使用命令行”,但是让您的 python 脚本subprocess在运行后执行命令papermill怎么样?与这个答案混合:

import subprocess

subprocess.call('jupyter nbconvert --to pdf --TemplateExporter.exclude_input=True Output.ipynb')

推荐阅读