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

How to save of the current state of a notebook in JupyterLab

我想将 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

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

如果它是一个新笔记本并且你运行它从上到下,你可以在最后一个单元格中使用以下命令:

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 此行可以根据您的 OS 进行更改。如果你在 windows,83 应该可以,否则你可能需要检查 's' 的键码,我发现最简单的方法是访问这个网站 http://keycode.info/ 并输入 s.

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