olastorp-ostra-goinge-skog

Convert a IPython Notebook into a Python file via command line

There are several ways to convert, start a 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 code cell in the 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

Posted

in

,

by

Tags:

Comments

4 responses to “Convert a IPython Notebook into a Python file via command line”

  1. Mohammad N ElNesr Avatar
    Mohammad N ElNesr

    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…

    1. torbjornzetterlund Avatar

      I appreciate the update

  2. Danny Teok Avatar
    Danny Teok

    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.

  3. maryam Avatar
    maryam

    thanks *-*

Leave a Reply

Your email address will not be published. Required fields are marked *