如何在JupyterLab中保存notebook的当前状态?

7

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

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

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

然而,nbconvert并没有获取当前笔记本,而是获取了笔记本上一次保存在磁盘上的状态。

所以,在尝试导出之前,我需要保存该状态。

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

%%javascript
IPython.notebook.save_notebook()

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

Javascript 错误:IPython 未定义

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

1个回答

9

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接