How do I convert a IPython Notebook into a Python file via commandline?
How do I convert a IPython Notebook into a Python file via commandline?
If you dont want to output a Python script every time you save, or you dont want to restart the IPython kernel:
On the command line, you can use nbconvert
:
$ jupyter nbconvert --to script [YOUR_NOTEBOOK].ipynb
As a bit of a hack, you can even call the above command in an IPython notebook by pre-pending !
(used for any command line argument). Inside a notebook:
!jupyter nbconvert --to script config_template.ipynb
Before --to script
was added, the option was --to python
or --to=python
, but it was renamed in the move toward a language-agnostic notebook system.
If you want to convert all *.ipynb
files from current directory to python script, you can run the command like this:
jupyter nbconvert --to script *.ipynb
How do I convert a IPython Notebook into a Python file via commandline?
Here is a quick and dirty way to extract the code from V3 or V4 ipynb without using ipython. It does not check cell types, etc.
import sys,json
f = open(sys.argv[1], r) #input.ipynb
j = json.load(f)
of = open(sys.argv[2], w) #output.py
if j[nbformat] >=4:
for i,cell in enumerate(j[cells]):
of.write(#cell +str(i)+n)
for line in cell[source]:
of.write(line)
of.write(nn)
else:
for i,cell in enumerate(j[worksheets][0][cells]):
of.write(#cell +str(i)+n)
for line in cell[input]:
of.write(line)
of.write(nn)
of.close()