Run Jupyter Notebook (.ipynb) from command line as if it were a .py file
Solution 1
You can send the jupyter nbconvert to stranded output and pipe that to python.
jupyter nbconvert --to script --execute --stdout test_nbconvert.ipynb | python
Solution 2
A workaround is a small shell script that has three parts
- converting the notebook
- executing created script
- removing the script
create a file runnb.sh
#!/bin/sh
# First argument is the notebook you would like to run
notebook=$1
scriptname="$(basename $notebook .ipynb)".py
jupyter nbconvert --to script --execute ${notebook} && python ${scriptname}
rm ${scriptname}
use as such:
$ ./runnb.sh nbconvert_test.ipynb
EDIT:
According to this answer, this command should do just fine jupyter nbconvert --execute test_nbconvert.ipynb
(just leav out the --to
flag
beniam
Updated on June 24, 2022Comments
-
beniam almost 2 years
I am authoring a Jupyter notebook on my local machine that will eventually be run on a remote server (which is running Ubuntu). Every time I need to make a change I must export the notebook as a
.py
file and then call it from the command line of the server.I'd like to be able to run this on the fly, calling one command that takes the current
.ipynb
file and executes it on the command line as if it were a.py
, showing all the print statements and output you'd expect if the.py
were run. I thoughtnbconverter
might do the trick using something like the following command:jupyter nbconvert --to script --execute nbconvert_test.ipynb
As it turnout, this does not convert the
.ipynb
to a.py
file to be executed on the command line as I would like, but rather it creates a new file callednbconvert_test.py
in the same directory which I would then have to run in a separate command. I'd really like to prevent the creation of that file every time I make even a small change, and to skip the extra step on the command line.Any help is appreciated!
-
beniam about 7 yearsThanks Robin-I think without the --to flag it creates an html file in the same directory that includes the output, but doesn't fit the bill exactly. Your script in three lines may do the trick. I'll pay with that now...Thanks.
-
beniam about 7 yearsThis doesn't seem to work for me. It returns a Syntax Error for invalid syntax
-
fizzyh2o about 7 yearstry piping to ipython instead of python? You might be using some ipython specific syntax in the notebook.
-
Raymond about 2 yearsIt doesn't work, it says xyz.py not found for rm command