0

I want to save a text version (.py) of a Jupyter notebook (.ipynb) without output for version control purposes.

I know you can do this by running jupyter nbconvert in terminal, but how can I automate this by executing this command from within the Jupyter notebook itself?

Also see Using IPython / Jupyter Notebooks Under Version Control

Kouichi C. Nakamura
  • 850
  • 3
  • 10
  • 25
  • Installing [Jupytext](https://jupytext.readthedocs.io/en/latest/index.html) (the [repo](https://github.com/mwouts/jupytext/tree/main)) also adds more features for making `.py` files from within Jupyter itself and using jupytext similar to on the command line by putting an exclamation point in front of the Jupytext [command line](https://jupytext.readthedocs.io/en/latest/using-cli.html) commands for running them from within an `.ipynb` cell. – Wayne Apr 20 '23 at 12:19

1 Answers1

0

You can save a text version (.py) of the notebook by adding this cell at the top of your Jupyter notebook. The Python file will be saved in the same folder. You can specify --output-dir if you like.

import os

nb_name = "mynotebook1.ipynb" #TODO change this to the file name of your Jupyter notebook

basename, ext = os.path.splitext(nb_name)
input_path = os.path.join(os.getcwd(), nb_name)

!jupyter nbconvert "{input_path}" --to="python" --output="{basename}"

According to this, the following also work with 2 cells

First cell

%%javascript
IPython.notebook.kernel.execute('nb_name = "' + IPython.notebook.notebook_name + '"')

Second cell

import os

basename, ext = os.path.splitext(nb_name)
input_path = os.path.join(os.getcwd(), nb_name)

!jupyter nbconvert "{input_path}" --to="python" --output="{basename}"

If you use this tool, you can make it with just one cell https://pypi.org/project/ipynbname/

import ipynbname
import os

nb_name= ipynbname.name()

basename, ext = os.path.splitext(nb_name)
input_path = os.path.join(os.getcwd(), nb_name)

!jupyter nbconvert "{input_path}" --to="python" --output="{basename}"
Kouichi C. Nakamura
  • 850
  • 3
  • 10
  • 25