How to run an .ipynb Jupyter Notebook from terminal?

I have some code in a .ipynb file and got it to the point where I don't really need the "interactive" feature of IPython Notebook. I would like to just run it straight from a Mac Terminal Command Line.

Basically, if this were just a .py file, I believe I could just do python filename.py from the command line. Is there something similar for a .ipynb file?


Solution 1:

nbconvert allows you to run notebooks with the --execute flag:

jupyter nbconvert --execute <notebook>

If you want to run a notebook and produce a new notebook, you can add --to notebook:

jupyter nbconvert --execute --to notebook <notebook>

Or if you want to replace the existing notebook with the new output:

jupyter nbconvert --execute --to notebook --inplace <notebook>

Since that's a really long command, you can use an alias:

alias nbx="jupyter nbconvert --execute --to notebook"
nbx [--inplace] <notebook>

Solution 2:

From the command line you can convert a notebook to python with this command:

jupyter nbconvert --to python nb.ipynb

https://github.com/jupyter/nbconvert

You may have to install the python mistune package:

sudo pip install -U mistune

Solution 3:

In your Terminal run ipython:

ipython

then locate your script and put there:

%run your_script.ipynb

Solution 4:

You can export all your code from .ipynb and save it as a .py script. Then you can run the script in your terminal.

code export sample

Hope it helps.

Solution 5:

Using ipython:

ipython --TerminalIPythonApp.file_to_run=<notebook>.ipynb

Normally, I would prefer this option as it is really self-describing. If you prefer to use less characters, use:

ipython -c "%run <notebook>.ipynb"

which is basically what Keto already suggested (unfortunately a little bit hidden) as a comment.