我想在我自己的网页中嵌入Jupyter的HTML输出。其原因主要在于,我可以使用自己的webapp中的Jupyter - 并通过互联网从世界上任何地方访问我的研究笔记本。
一个典型的用例场景是我点击页面上的一个按钮,我的页面中会插入一个iframe;然后Jupyter将在后端启动(如果尚未运行),Jupyter的输出将被“管道”到iframe - 这样我就可以在我的页面中使用Jupyter。
它出现的天真解决方案是使用<iframe>
,但有两个问题:
无论如何我可以克服这些问题,所以我可以将Jupyter的输出嵌入到我自己的网页中吗?
你需要检查nbconvert - https://github.com/jupyter/nbconvert
你有2个选择。
这里是短代码:如果你想显示已经生成:
from nbconvert.preprocessors import ExecutePreprocessor
import nbformat
from nbconvert import HTMLExporter
from nbconvert.preprocessors.execute import CellExecutionError
src_notebook = nbformat.reads(ff.read(), as_version=4) #where ff is file opened with some open("path to notebook file")
html_exporter = HTMLExporter()
html_exporter.template_file = 'basic' #basic will skip generating body and html tags.... use "all" to gen all..
(body, resources) = html_exporter.from_notebook_node(src_notebook)
print(body) #body have html output
如果你还想运行笔记本,那么:
from nbconvert.preprocessors import ExecutePreprocessor
import nbformat
from nbconvert import HTMLExporter
from nbconvert.preprocessors.execute import CellExecutionError
src_notebook = nbformat.reads(ff.read(), as_version=4) #where ff is file opened with some open("path to notebook file")
ep = ExecutePreprocessor(timeout=50, kernel_name='python3')
ep.preprocess(src_notebook, {})
html_exporter = HTMLExporter()
html_exporter.template_file = 'basic' #basic will skip generating body and html tags.... use "all" to gen all..
(body, resources) = html_exporter.from_notebook_node(src_notebook)
print(body) #body have html output
您可以使用html_embed
预处理器直接执行此操作:
$ jupyter nbconvert --to html_embed Annex.ipynb
[NbConvertApp] Converting notebook Annex.ipynb to html_embed
/usr/local/lib/python3.6/site-packages/nbconvert/filters/datatypefilter.py:41: UserWarning: Your element with mimetype(s) dict_keys(['image/pdf']) is not able to be represented.
mimetypes=output.keys())
[NbConvertApp] Writing 2624499 bytes to Annex.html
奇怪的是,我找不到来自nbconvert的manual中的直接引用。