Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cause Jupyter Lab to save notebook (programmatically)

I have a notebook that runs overnight, and prints out a bunch of stuff, including images and such. I want to cause this output to be saved programatically (perhaps at certain intervals). I also want to save the code that was run. In a Jupyter notebook, you could do:

from IPython.display import display, Javascript
display(Javascript('IPython.notebook.save_checkpoint();'))
# causes the current .ipynb file to save itself (same as hitting CTRL+s)

(from Save an IPython notebook programmatically from within itself?)

Although, I found that this javascript injection did not work in Jupyter lab(Jupyter not found). My question is how to do the equivalent of the above code in Jupyter lab. Upon inspecting the HTML of the jupyter lab, I could not find the Jupyter object.

like image 776
charles strauss Avatar asked Mar 31 '21 02:03

charles strauss


2 Answers

You can use ipylab to access JupyterLab API from Python. To save the notebook just invoke the docmanager:save command:

from ipylab import JupyterFrontEnd

app = JupyterFrontEnd()
app.commands.execute('docmanager:save')

You can get the full list of commands with app.commands.list_commands().

like image 163
krassowski Avatar answered Sep 18 '22 10:09

krassowski


I just wanted to share a really small tweak of the other solution by krassowski that works for JupyterLab on MacOS:

from IPython.display import display, HTML

script = """
this.nextElementSibling.focus();
this.dispatchEvent(new KeyboardEvent('keydown', {key:'s', keyCode: 83, metaKey: true}));
"""
display(HTML((
    '<img src onerror="{}" style="display:none">'
    '<input style="width:0;height:0;border:0">'
).format(script)))
like image 27
dnola Avatar answered Sep 20 '22 10:09

dnola