'Stopping Program in Jupyter

I'm using the Jupyter (previously iPython Notebooks) environment, with Python 3, and I want a program to terminate early.

Usually in Python, I'd just do a raise SystemExit or sys.exit().

However, in the Jupyter environment, I'm stuck with the ugly message "An exception has occurred, use %tb to see the full traceback." Is there a way in Jupyter to just tell the program to terminate immediately, without error?

Thanks.



Solution 1:[1]

I recently had this same problem. My solution is to use return like this:

if __name__ == '__main__':
    # Some code
    if something_went_wrong:
        return

    # Carry on if nothing happened.

This allows the code to stop without killing the kernel or giving you the ugly stack trace.

Solution 2:[2]

If you're using the web interface, simply hit the interrupt kernel button in the toolbar. This throws a KeyboardInterrupt and immediately stops execution of the cell.

Solution 3:[3]

If you're running the notebook programatically with nbconvert, consider setting up a custom Exception (or something like KeyboardInterrupt), raising it in the notebook, running the notebook using the nbconvert python api (ref), catching the exception, and not bubbling it.

Example (untested) code:

Notebook notebook.ipynb:

Cell 1: print("foo")
Cell 2: from main import EarlyReturn; raise EarlyReturn
Cell 3: print("bar")

main.py:

class EarlyReturn(Exception):
    pass


def run_notebook(notebook_filename):
    import nbformat
    from nbconvert.preprocessors import ExecutePreprocessor
    from nbconvert.preprocessors import CellExecutionError

    with open(notebook_filename) as f:
        nb = nbformat.read(f, as_version=4)

    ep = ExecutePreprocessor(timeout=600, kernel_name='python3')
    try:
        ep.preprocess(nb, {'metadata': {'path': 'notebooks/'}})
    except CellExecutionError as e:
        if e.ename == 'EarlyReturn':
            pass
        else:
            msg = 'Error executing the notebook "%s".\n\n' % notebook_filename
            msg += 'See notebook "%s" for the traceback.\n\n' % "executed_notebook.ipynb"
            print(msg)
            raise

    finally:
        with open('executed_notebook.ipynb', 'w', encoding='utf-8') as f:
            nbformat.write(nb, f)


if __name__ == '__main__':
    run_notebook('notebook.ipynb')

and run the notebook as: python3 main.py

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matthew Hall
Solution 2
Solution 3