jupyter-notebookjupyteripython

Jupyter notebook shell command/line magic failure does not cause cell failure


I'm using a Jupyter notebook as a tutorial for a command-line tool. However, I noticed that regardless of whether I use a shell command (!) or line magic (%), an error does not cause the cell to fail, and the execution simply continues. For example:

!pip install foo
%pip install foo

Is there any way to cause these errors to be fatal instead of continuing on to the next cell to execute?


Solution

  • You want the code in the 'install cell' to be:

    %pip install foo
    import foo
    

    Then it won't continue on after failing to install.

    Technically, this more general solution also allows what you want when using an ipykernel:

    %%bash
    pip install foo
    

    (For Windows users, you may want to try %%cmd instead of %%bash.)

    That should generalize to more command line executions that fail.

    However, because of reasons I put in my comments to the original post, this would be bad to teach learners to use pip this way.