如何在JupyterLab notebook内部通过代码自动保存当前notebook?
JupyterLab 环境下实现Notebook自保存的代码修改方案
你遇到的
Javascript Error: IPython is not defined报错,是因为JupyterLab 不再兼容经典Jupyter Notebook的IPython.notebook全局JS对象,原有代码里的JS调用逻辑不适配新的前端接口规范。
修改后的适配代码如下:
import time from IPython.display import display, Javascript import hashlib def save_notebook(file_path): start_md5 = hashlib.md5(open(file_path,'rb').read()).hexdigest() # 替换为JupyterLab支持的保存命令 display(Javascript('window.jupyterapp.commands.execute("docmanager:save")')) current_md5 = start_md5 while start_md5 == current_md5: time.sleep(1) current_md5 = hashlib.md5(open(file_path,'rb').read()).hexdigest()
使用注意事项:
- 该代码仅在有前端交互的JupyterLab页面环境下生效,无前端的后台运行、定时运行场景无法触发JS执行,也就不能实现自动保存
- 传入的
file_path必须是当前正在编辑运行的Notebook文件的本地完整路径,否则MD5校验逻辑会失效 - 如果你使用的是3.x以下的旧版本JupyterLab,执行仍报错的话,可以把JS语句替换为
document.querySelector('[title="Save the notebook contents (Ctrl+S)"]').click(),通过模拟点击保存按钮实现相同效果
内容的提问来源于stack exchange,提问作者S-UP
相关产品推荐
相关产品推荐

