首页 > 解决方案 > Jupyter - 将当前的 ipynb 文件导出到笔记本中的 html

问题描述

我正在尝试在我的 jupyter 笔记本中编写 python 代码,这会将整个当前笔记本导出为 html/pdf。

我知道我可以做这样的事情:

import subprocess
subprocess.call("jupyter nbconvert notebook.ipynb")

但这需要文件名,这在 notebook 中是未知的

我看到了很多“hacks”来获取笔记本文件名,比如这个: How do I get the current IPython Notebook name 但我更喜欢找到更好的解决方案。

有没有一种聪明的方法可以将当前运行的笔记本导出为 html/pdf 文件?

谢谢。

标签: pythonipythonjupyter-notebookjupyter

解决方案


您可以使用库papermill,它将使用摄取的参数执行笔记本(基本上是您在笔记本之外定义的笔记本名称)

Python程序

pm.execute_notebook(
   'notebooks/notebookA.ipynb', # notebook to execute
   'notebooks/temp.ipynb', # temporary notebook that will contains the outputs and will be used to save HTML
   report_mode=True, # To hide ingested parameters cells, but not working for me
   parameters=dict(filename_ipynb='notebooks/temp.ipynb', 
                   filename_html='output/notebookA.html')
)

/notebooks/notebookA.ipynb

(插入笔记本的最后一个单元格)

import os
os.system('jupyter nbconvert --output ../' + filename_html + ' --to html ' + filename_ipynb)

只是一件事:它正在添加一个单元格来设置摄取的参数。它应该能够用 report_mode=False 隐藏它,但不知何故它不起作用,即使它应该:https ://github.com/nteract/papermill/issues/253


推荐阅读