Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jupyter: how to stop execution on errors?

Tags:

python

jupyter

The common way to defensively abort execution in python is to simply do something like:

if something_went_wrong:
    print("Error message: goodbye cruel world")
    exit(1)

However, this is not good practice when using jupyter notebook, as this seems to abort the kernel entirely, which is not always wanted. Is there are proper/better way in jupyter, besides hack-y inifinte loops?

like image 545
gustafbstrom Avatar asked May 28 '16 20:05

gustafbstrom


People also ask

How do you stop an execution in a Jupyter notebook?

Stopping a process or restarting a Jupyter Notebook To interrupt a cell execution, you can click the ■ “stop” button in the ribbon above the notebook, or select “Interrupt Kernel” from the Kernel menue.

How do I interrupt in Jupyter?

To interrupt a calculation which is taking too long, use the Kernel, Interrupt menu option, or the i,i keyboard shortcut. Similarly, to restart the whole computational process, use the Kernel, Restart menu option or 0,0 shortcut.

How do you suppress warnings in Jupyter lab?

simplefilter('ignore') in order to suppress warnings.

How do I stop the Jupyter notebook infinite loop?

Q: How to stop a long-running command, such as an infinite loop. You can try pressing the Stop button on the toolbar at the top of the browser window to stop any activity the Notebook is currently processing.


1 Answers

No, exit() is not the way to abort Python execution usually. exit() is meant to stop the interpreter immediately with a status code.

Usually, you will write a script like that:

 if __name__ == '__main__':
     sys.exit(main())

Try not to put sys.exit() in the middle of your code — it is bad practice, and you might end up with non closed filehandle or locked resources.

To do what you want, just raise an exception of the correct type. If it propagate to the eval loop, IPython will stop the notebook execution.

Also, it will give you useful error messages and a stack trace.

if type(age) is not int:
    raise TypeError("Age must be an integer")
elif age < 0:
    raise ValueError("Sorry you can't be born in the future")
else :
    ...

You can even inspect the stack post-mortem with %debug to see what went wrong where, but that is another subject.

like image 179
Matt Avatar answered Sep 28 '22 01:09

Matt