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?
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.
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.
simplefilter('ignore') in order to suppress warnings.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With