Reputation: 1547
How do you convert an IPython notebook file (json with .ipynb
extension) into a regular .py
module?
Upvotes: 142
Views: 382989
Reputation: 9780
Jupytext allows for such a conversion on the command line, and importantly you can go back again from the script to a notebook (even an executed notebook). See here.
In addition to from the command line, installed Jupytext can make corresponding pairs of files automatically, and has a pre-commit hook option that you can use if you use GitHub in conjuction with your efforts. See here about the pre-commit hook.
Upvotes: 1
Reputation: 7563
just adding my 2 cents to all the valid answers.
It is possible to create a hook on the Jupyter notebook so that every time the notebook is saved it generates/updates the python file from the notebook
First you need to generate a config
jupyter notebook --generate-config
This creates a file in /User/your-user/.jupyter/jupyter_notebook_config.py
Then you update this file with your hook
import os
from subprocess import run
def post_save(model, os_path, contents_manager, **kwargs):
"""Automatically convert .ipynb to .py using jupytext on save."""
if model['type'] == 'notebook':
# Run the jupytext command to convert the notebook to .py
run(['jupytext', '--to', 'py', os_path])
c.FileContentsManager.post_save_hook = post_save
Restart the Jupyter notebook, open it, add things and save. A new file .py is generated every time you save the Jupyter notebook. I hope it is useful!
Upvotes: 0
Reputation: 1036
According to https://ipython.org/ipython-doc/3/notebook/nbconvert.html you are looking for the nbconvert command with the --to script option.
ipython nbconvert notebook.ipynb --to script
EDIT:
as per the comments, this is now updated to
jupyter nbconvert mynotebook.ipynb --to python
Upvotes: 47
Reputation: 59
Ctrl + s
to save it to wherever you want.Upvotes: 4
Reputation: 4647
My version of Jupyter Notebook, 3.3.2, has this option on the File Menu:
Upvotes: 2
Reputation: 111
jupyter nbconvert [filename].ipynb --no-prompt --to python
The above code will generate [filename].py in the same directory
Upvotes: 1
Reputation: 1920
well first of all you need to install this package below:
sudo apt install ipython
jupyter nbconvert --to script [YOUR_NOTEBOOK].ipynb
two options are available either --to python or --to=python
for me this works fine:
jupyter nbconvert --to python while.ipynb
[NbConvertApp] Converting notebook while.ipynb to python
[NbConvertApp] Writing 758 bytes to while.py
pip3 install ipython
if it does not work for you try, by pip3.
pip3 install ipython
Upvotes: 4
Reputation: 14075
If this is a one-off, follow e.g. @kikocorreoso depending if you want to use command line or gui.
However, if you want some solution that will maintain a synchronized version of the .py and the .ipynb you really should consider using jupytext as also pointed out by @Wayne
Run conda install jupytext
or pip install jupytext
Then do:
jupytext --set-formats ipynb,py <file>.ipynb
To keep it synchronized to the .py file:
jupytext --set-formats ipynb,py <file>.ipynb --sync
This will make sure jupyter keeps the two files in sync when saving from now on...
Last note: If you are a gui person, after running the installation command for jupytext, everything else can be done from the gui as well File-->Jupytext-->pair Notebook with light Script
:
Upvotes: 2
Reputation:
Tested on Ubuntu 20.04
Install required packages for PIP
$ pip install ipython
$ pip install nbconvert
To install required packages
$ sudo apt-get install texlive-xetex texlive-fonts-recommended texlive-plain-generic
Use jupyter nbconvert command to convert to different format
Source file pro.ipynb
To convert to ascii
$ jupyter nbconvert --to asciidoc pro.ipynb
To convert to pdf
$ jupyter nbconvert --to pdf pro.ipynb
To convert to python
$ jupyter nbconvert --to python pro.ipynb
Convert ipynb project through python code use savefig method of pyplot:
import matplotlib.pyplot as plt
%matplotlib inline
exp_vals=[1400,600,300,410,250]
exp_labels=['Home Rent','Food','Phone/Internet Bill','Car','Other Utilities']
plt.axis('equal')
plt.pie(exp_vals,labels=exp_labels,radius=2,autopct='%0.1f%%',shadow=True,explode=[0,0.5,0,0.3,0],startangle=20)
# plt.show()
plt.savefig('piechart.jpg',bbox_inches='tight',pad_inches=2,transparent=True,edgecolor='r')
piechart.png image that it generated:
Hope this helps to convert your ~(`)/\/\/\_ [Python] code
Upvotes: 4
Reputation: 501
Convert the Ipynb dir files to .py
import os
for fname in os.listdir():
if fname.endswith('ipynb'):
os.system(f'jupyter nbconvert {fname} --to python')
Upvotes: 1
Reputation: 79
You can run a .py file in the same directory:
import json
files = ["my_first_file_name.ipynb", "my_second_file_name.ipynb"]
for file in files:
code = json.load(open(file))
py_file = open(f"{file}.py", "w+")
for cell in code['cells']:
if cell['cell_type'] == 'code':
for line in cell['source']:
py_file.write(line)
py_file.write("\n")
elif cell['cell_type'] == 'markdown':
py_file.write("\n")
for line in cell['source']:
if line and line[0] == "#":
py_file.write(line)
py_file.write("\n")
py_file.close()
I rewrite this code from Syrtis Major's answer.
Upvotes: 7
Reputation: 362
you can use this to do that :
pip install ipynb-py-convert
then run this on your terminal to convert .py file to .ipynb :
ipynb-py-convert Ex/abc.py Ex/abc.ipynb
to convert .ipynb files to .py :
ipynb-py-convert Ex/abc.ipynb Ex/abc.py
Upvotes: 19
Reputation: 1406
One way to do that would be to upload your script on Colab and download it in .py format from File -> Download .py
Upvotes: 1
Reputation: 53
Copy all the (''.ipynb) files in the Desired folder then execute:
import os
desired_path = 'C:\\Users\\Docs\\Ipynb Covertor'
os.chdir(desired_path)
list_of_directory = os.listdir(desired_path)
for file in list_of_directory:
os.system('ipython nbconvert --to script ' + str(file))
Upvotes: 0
Reputation: 427
You definitely can achieve that with nbconvert using the following command:
jupyter nbconvert --to python while.ipynb
However, having used it personally I would advise against it for several reasons:
So to summarize, there is not good way to out of the box convert python notebooks to maintainable, robust python modularized code, the only way is to manually do surgery.
Upvotes: 3
Reputation: 1110
Upvotes: 1
Reputation: 3929
You can use the following script to convert jupyter notebook to Python script, or view the code directly.
To do this, write the following contents into a file cat_ipynb
, then chmod +x cat_ipynb
.
#!/usr/bin/env python
import sys
import json
for file in sys.argv[1:]:
print('# file: %s' % file)
print('# vi: filetype=python')
print('')
code = json.load(open(file))
for cell in code['cells']:
if cell['cell_type'] == 'code':
print('# -------- code --------')
for line in cell['source']:
print(line, end='')
print('\n')
elif cell['cell_type'] == 'markdown':
print('# -------- markdown --------')
for line in cell['source']:
print("#", line, end='')
print('\n')
Then you can use
cat_ipynb your_notebook.ipynb > output.py
Or show it with vi
directly
cat_ipynb your_notebook.ipynb | view -
Upvotes: 2
Reputation: 73588
In short: This command-line option converts mynotebook.ipynb
to python
code:
jupyter nbconvert mynotebook.ipynb --to python
note: this is different from above answer. ipython
has been renamed to jupyter
. the old executable name (ipython) is deprecated.
More details:
jupyter
command-line has an nbconvert
argument which helps convert notebook files (*.ipynb)
to various other formats.
You could even convert it to any one of these formats using the same command but different --to
option:
the same command jupyter nbconvert --to latex mynotebook.ipynb
For more see jupyter nbconvert --help
. There are extensive options to this. You could even to execute the code first before converting, different log-level options etc.
Upvotes: 41
Reputation: 4219
From the notebook menu you can save the file directly as a python script. Go to the 'File' option of the menu, then select 'Download as' and there you would see a 'Python (.py)' option.
Another option would be to use nbconvert from the command line:
jupyter nbconvert --to script 'my-notebook.ipynb'
Have a look here.
Upvotes: 190