如何在 JupyterLab 中保存笔记本的当前状态

时间:2021-02-08 22:41:04

标签: python html jupyter-lab nbconvert

我想将 JupyterLab 笔记本(不是 Jupyter 笔记本)导出为 HTML。

我在笔记本内部使用以下代码,正确导出笔记本:

os.popen('jupyter nbconvert current_notebook.ipynb --to html').read()

但是,nbconvert 不是获取当前笔记本,而是获取笔记本上次保存在磁盘上的状态。

因此,我需要在尝试导出状态之前保存状态。

我正在尝试使用以下代码:

%%javascript
IPython.notebook.save_notebook()

但显然 JupyterLab 不支持 JS API,因此返回以下消息:

Javascript Error: IPython is not defined

您知道在导出笔记本之前保存当前状态的方法吗?

1 个答案:

答案 0 :(得分:10)

如果是全新的 notebook,并且从上到下运行,则可以在最后一个单元格中使用以下命令:

import os
%notebook -e test.ipynb
os.system('jupyter nbconvert --to html test.ipynb')

它会给出一个 test.html 文件。

或者,您可以使用 javascript 和 HTML 来模拟 CTRL + s 事件,

from IPython.display import display, HTML

### emulate Ctrl + s
script = """
this.nextElementSibling.focus();
this.dispatchEvent(new KeyboardEvent('keydown', {key:'s', keyCode: 83, ctrlKey: true}));
"""
display(HTML((
    '<input style="width:0;height:0;border:0">'
).format(script)))

import os

os.system('jupyter nbconvert --to html test.ipynb') # here, test is the name of your notebook

现在,keyCode: 83 此行可以根据您的操作系统进行更改。如果您使用的是 Windows,则应该使用 83,否则您可能需要检查“s”的键码,我发现最简单的方法是访问此网站 http://keycode.info/ 并输入 s

参考:https://unixpapa.com/js/key.html