How to stop a Jupyter notebook from one of its Python cell?
Feb 3, 11:43pm

To stop a Jupyter notebook from within one of its Python cells, you can use one of the following methods:

1. Interrupt the Kernel

You can programmatically interrupt the kernel (i.e., stop the notebook execution) by running:

python
import os os._exit(00)

This will immediately terminate the Python process.


2. Raise a KeyboardInterrupt

You can simulate a keyboard interrupt (like pressing Ctrl+C in a terminal) with:

python
raise KeyboardInterrupt

This will stop the current cell and return you to the notebook interface.


3. Use IPython Magic Commands

If you want to stop the notebook from a specific cell, you can use:

python
%%javascript IPython.notebook.kernel.execute('IPython.notebook.kernel.interrupt()');

This uses JavaScript to interrupt the kernel.


4. Restart the Kernel

If you want to restart the kernel (not just stop the current cell), you can use:

python
from IPython.display import display, HTML display(HTML("<script>Jupyter.notebook.kernel.restart()</script>"))

This will restart the kernel, stopping all execution.


Note: Methods 1 and 2 are more direct and will stop the notebook immediately, while methods 3 and 4 are more interactive and may require the notebook to be in a specific state. Use the method that best fits your needs!

Feb 3, 11:43pm

This Chat is read-only. Login to resume chatting.

from IPython.display import display, HTML display(HTML("<script>Jupyter.notebook.kernel.restart()</script>"))