https://torbjornzetterlund.com/wp-content/uploads/2014/05/python-e1399275796649-960x600_c.jpeg

Convert a IPython Notebook into a Python file via command line


There are several ways to convert, start notebook with –script flag will save .py file alongside .ipynb on every save. You can also (as ipynb is json), load it, loop through it and eval codecell in current namespace.

If you don’t want to output a Python script every time you save, or you don’t want to restart the IPython kernel:

On the command line, you can use nbconvert:

$ ipython nbconvert --to=python [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:

!ipython nbconvert --to=python config_template.ipynb

3 Responses

  • Mohammad N ElNesr on December 6, 2016, 09:51:57

    Thank you very much for this post,
    I just want to update it to the latest version as the iPython is now Jupyter, and I want to add an additional note:
    If you want to convert a file learn_to_code.ipynb that is located in C:\Users\User\Documents\Codes
    Please follow the following:
    1- Launch the command prompt preferably as Administrator.
    2- type ‘cd C:\Users\User\Documents\Codes’ or replace this path with yours, then press Enter.
    3- type the following ‘jupyter nbconvert –to python learn_to_code.ipynb’, then press Enter.
    That’s it; you will find a file named learn_to_code.py in the same directory.
    * If you want to do this for multiple files, you can create a notepad file with their names preceded with ‘jupyter nbconvert –to python ‘ then save the file as .bat and double click on it.

    Thanks…

    Reply to Mohammad
  • Danny Teok on March 31, 2017, 11:43:32

    Just want to point out a typo in Mo’s reply, albeit trivial, but for the benefit of those who’d normally skims through quickly.
    1. Open cmd as Adminstrator
    2. Navigate to directory where you want to convert
    3. jupyter nbconvert –to=python “filename.ipynb”

    You could convert to html, pdf, etc. See its help manual for this.

    Reply to Danny

Menu