IPython Notebook - early exit from cell
I'm reposting my answer from here because the solution should apply to your question as well. It will...
- not kill the kernel on exit
- not display a full traceback (no traceback for use in IPython shell)
- not force you to entrench code with try/excepts
- work with or without IPython, without changes in code
Just import 'exit' from the code beneath into your jupyter notebook (IPython notebook) and calling 'exit()' should work. It will exit and letting you know that...
An exception has occurred, use %tb to see the full traceback.
IpyExit
"""
# ipython_exit.py
Allows exit() to work if script is invoked with IPython without
raising NameError Exception. Keeps kernel alive.
Use: import variable 'exit' in target script with
'from ipython_exit import exit'
"""
import sys
from io import StringIO
from IPython import get_ipython
class IpyExit(SystemExit):
"""Exit Exception for IPython.
Exception temporarily redirects stderr to buffer.
"""
def __init__(self):
# print("exiting") # optionally print some message to stdout, too
# ... or do other stuff before exit
sys.stderr = StringIO()
def __del__(self):
sys.stderr.close()
sys.stderr = sys.__stderr__ # restore from backup
def ipy_exit():
raise IpyExit
if get_ipython(): # ...run with IPython
exit = ipy_exit # rebind to custom exit
else:
exit = exit # just make exit importable
How to stop python program once condition is met (in jupyter notebook)
try this instead of sys.exit()
:
raise SystemExit("Stop right there!")
Ipython Notebook: Elegant way of turning off part of cells?
Using Jupyter notebook you can click on a cell, press esc
and then r
. That converts it to a "raw" cell. Similar thing can be done to convert it back, esc
+ y
. No comments needed, just key presses.
Within Jupyer notebook, go to Help -> Keyboard shortcuts for more.
Here's a snippet:
Command Mode (press
Esc
to enable)
↩ : enter edit mode
⇧↩ : run cell, select below
⌃↩ : run cell
⌥↩ : run cell, insert below
y : to code
m : to markdown
r : to raw
Related Topics
Python Regex - Finding Phone Number
Sum Numbers of Each Row of a Matrix Python
Python/Regex - How to Extract Date from Filename Using Regular Expression
Jsondecodeerror: Expecting Value: Line 1 Column 1 (Char 0)
Paramiko Capturing Command Output
How to Prevent Brokenpipeerror When Doing a Flush in Python
Valueerror: Feature_Names Mismatch: in Xgboost in the Predict() Function
How to Format an Integer to a Two Digit Hex
How to Change a Two Dimensional Array to One Dimensional
How to Remove Unused Packages from Virtualenv
How to Find Consecutive Numbers in a Python List
Merge Multiple Rows to Single Row - Pandas
Changing Value in Data Frame Column in a Loop Python
Python Comparing List Values to Keys in List of Dicts
How to Write Python Array (Data = []) to Excel
How to Create a for Loop That Goes Through All Diagonal Possibilities of a List
Finding the Maximum Number of Columns in a File or CSV Using Python