Can a Jupyter notebook programmatically halt itself, such that the notebook no longer appears in the "Running" tab?
At the end of a notebook "Run All", I would like the last notebook cell to contain code, and for that code to trigger the equivalent of:
Can this be done with javascript, or with %magic, or something else?
I am running the latest Docker image Jupyer Datascience Notebook, not JupyterHub.
(Responded on the mailing list)
Yes, a Jupyter notebook can programmatically halt itself.
Use a cell at the end of an iPython notebook like this:
%%javascript
Jupyter.notebook.session.delete();
Restart the stopped notebook with:
A demo ipynb file is posted on the forum thread
This led to a question: should it be possible to use exit() to stop the kernel in a notebook? At present, using exit() will make the notebook think that the kernel has died, and it will automatically start a new kernel. I think that exit() should probably put the notebook interface into the state it arrives in if it gives up on trying to start a kernel.
As a current workaround for those interested in notebook halting, I developed this %%javascript cell for use at the end of a Run All sequence. It uses a modal dialog to halt the notebook kernal (and optionally restart it on user click).
Notebook Halt / Restart cell
_When included at the bottom of a notebook, it will stop the notebook at the end of Run All, and pop up a modal dialog letting the user know that the notebook was auto-stopped at the end of the run. The dialog offers a "Kernel Restart" button which restarts the notebook._
%%javascript
require(
["base/js/dialog"],
function(dialog) {
dialog.modal({
title: 'Notebook Halted',
body: 'This notebook is no longer running; the kernel has been halted. Close the browser tab, or, to continue working, restart the kernel.',
buttons: {
'Kernel restart': { click: function(){ Jupyter.notebook.session.restart(); } }
}
});
}
);
Jupyter.notebook.session.delete();
Related to this, in #2070, which was recently merged, I added a "Shutdown" menu item to the Kernel menu.
Hey there, I'm going through old issues and it seems to me that it makes sense to close this one.
@jeremydouglass figured out a workaround in the forum link posted two comments above this one, and I added "Shutdown" item to the Kernel menu.
Thanks everyone and happy hacking! :bowtie:
u can use for a specific cell
assert False
Most helpful comment
Yes, a Jupyter notebook can programmatically halt itself.
Use a cell at the end of an iPython notebook like this:
Restart the stopped notebook with:
A demo ipynb file is posted on the forum thread