MarcelSimon
MarcelSimon

Reputation: 602

How to stop execution of all cells in Jupyter Notebook

Suppose I executed all cells in a Jupyter Notebook, and want to interrupt the computation in the middle. How can I stop the execution of all cells?

"Kernel interrupt" only interrupts the execution of the current cell, but then immediately continues with all remaining cells. Instead, I do not want to execute all remaining cells after hitting "Kernel interrupt". How can I do that?

I am running version 4.2.3 with Python 3.5.2, packaged by conda-forge

Upvotes: 30

Views: 54538

Answers (7)

nico
nico

Reputation: 1332

raise SystemExit from dCSeven is a good solution. If you don’t want to see the Python error message, you can wrap your code in a try..except block.

def do_what_you_have_to_do():
    i_want_to_stop = True
    if i_want_to_stop:
        raise SystemExit("I just wanted to stop!")

try:
    do_what_you_have_to_do()
except SystemExit as _e:
    print(_e)

Upvotes: 0

Praveer Kumar
Praveer Kumar

Reputation: 1008

enter image description here

we can just click on the interrupt the kernel it will stop the computation.

Upvotes: 1

Jason210
Jason210

Reputation: 3350

I think the simplest solution is to just use assert False which stops execution at that point in the code. The best practice is to put this in a cell of its own, so you can stop and start the code around this.

Upvotes: 1

Romeo Kienzler
Romeo Kienzler

Reputation: 3539

I'm using exit() since to me it is cleaner than raising an exception

Upvotes: 1

user13459274
user13459274

Reputation:

One simple trick to get rid of this problem, is to press "ctrl+a" to select all the code of that particular cell you want to stop the execution of and press "ctrl+x" to cut the entire cell code.
Now the cell is empty and just the empty cell is executed.
Afterwards just paste the code by "ctrl+v" and now your problem would be solved.

Upvotes: -3

Apostolos
Apostolos

Reputation: 3445

Put in comment (highlight and press Ctrl-/) the instruction(s) responsible for running -- or, faster, comment the whole cell -- and re-run the cell (Ctrl-Enter). This will stop running and of course the output. You can then un-comment the affected part. This is much less painful than killing and restarting the kernel.

(Note that just clearing the output with [Esc]+'O' won't stop it.)

Upvotes: 0

dCSeven
dCSeven

Reputation: 905

If you know it beforehand, where you want to stop (e.g have code below that takes long and doesn't need to be executed every run), you can add a

    raise SystemExit("Stop right there!")

whereever you want to stop.

Everything below isn't executed, since an exception has been thrown and when using the SystemExit Exception no stacktrace is shown by default.
The kernel doesn't exit, so you can still execute everything by hand afterwards.

Upvotes: 51

Related Questions