我有一个Python笔记本,可以通过命令行成功地导出到HTML:
$ jupyter nbconvert nb.ipynb --template toc2我如何做到同样的,但通过编程(通过API)?
这就是我到目前为止所取得的成就:
import os
import nbformat
from nbconvert import HTMLExporter
from nbconvert.preprocessors import ExecutePreprocessor
nb_path = './nb.ipynb'
with open(nb_path) as f:
nb = nbformat.read(f, as_version=4)
ep = ExecutePreprocessor(kernel_name='python3')
ep.preprocess(nb)
exporter = HTMLExporter()
html, _ = exporter.from_notebook_node(nb)
output_html_file = f"./nb.html"
with open(output_html_file, "w") as f:
f.write(html)
f.close()
print(f"Result HTML file: {output_html_file}")它成功地导出了HTML,但是没有内容表。我不知道如何通过API设置--template toc2。
发布于 2020-10-17 19:49:35
我找到了两种方法
最忠实地复制$ jupyter nbconvert nb.ipynb --template toc2的方法包括使用toc2.tpl模板文件设置HTMLExporter().template_file属性。
<base filepath>/Anaconda3/Lib/site-packages/jupyter_contrib_nbextensions/templates/toc2.tplfrom nbconvert import HTMLExporter
from nbconvert.writers import FilesWriter
import nbformat
from pathlib import Path
input_notebook = "My_notebook.ipynb"
output_html ="My_notebook"
toc2_tpl_path = "<base filepath>/Anaconda3/Lib/site-packages/jupyter_contrib_nbextensions/templates/toc2.tpl"
notebook_node = nbformat.read(input_notebook, as_version=4)
exporter = HTMLExporter()
exporter.template_file = toc2_tpl_path # THIS IS THE CRITICAL LINE
(body, resources) = exporter.from_notebook_node(notebook_node)
write_file = FilesWriter()
write_file.write(
output=body,
resources=resources,
notebook_name=output_html
)另一种方法是在TocExporter模块中使用nbconvert_support类,而不是HTMLExporter。
jupyter nbconvert --to html_toc nb.ipynb,而不是设置标准HTML方法的模板。toc2.tpl的不同文件路径from nbconvert import HTMLExporter
from nbconvert.writers import FilesWriter
import nbformat
from pathlib import Path
from jupyter_contrib_nbextensions.nbconvert_support import TocExporter # CRITICAL MODULE
input_notebook = "My_notebook.ipynb"
output_html ="My_notebook"
notebook_node = nbformat.read(input_notebook, as_version=4)
exporter = TocExporter() # CRITICAL LINE
(body, resources) = exporter.from_notebook_node(notebook_node)
write_file = FilesWriter()
write_file.write(
output=body,
resources=resources,
notebook_name=output_html
)最后,我想向其他人提一下我的动机。我工作的机器之一使用Windows,因此要获得命令提示符来运行jupyter命令,需要对Windows PATH环境造成一些干扰,这让人头疼。我可以通过使用Anaconda提示符来解决这个问题,但这需要每次打开提示符并输入full命令。我可以尝试用os.system()编写脚本,但这会调用默认的命令行(Windows命令提示符),而不是Anaconda提示符。上面的方法允许我通过在任何笔记本中运行一个简单的python脚本将木星笔记本转换为带有TOCs和嵌入式图形的HTML。
发布于 2020-07-09 13:34:14
文档中并不清楚这一点,但是TemplateExporter类的构造函数提到了以下内容:
template_file : str (可选,kw arg) 导出时要使用的模板。
在测试它之后,我可以确认您所需要做的就是为您的导出程序将filepath添加到此参数下的模板文件中。
HTMLExporter(template_file=path_to_template_file)https://stackoverflow.com/questions/61658289
复制相似问题