Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Save iPython session to a python file as code

Save an iPython session commands/code to a file

You must use the magic method %save:

In [1]: %save?
Type:       Magic function
String Form:<bound method of <IPython.core.magics.code.CodeMagics object at 0x7fb5d25bb1d0>>
Namespace:  IPython internal
File:       /usr/lib/python2.7/dist-packages/IPython/core/magics/
Definition: %save(self, parameter_s='')
Save a set of lines or a macro to a given filename.

  %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...


  -r: use 'raw' input.  By default, the 'processed' history is used,
  so that magics are loaded in their transformed version to valid
  Python.  If this option is given, the raw input as typed as the
  command line is used instead.
  -f: force overwrite.  If file exists, %save will prompt for overwrite
  unless -f is given.

  -a: append to the file instead of overwriting it.

This function uses the same syntax as %history for input ranges,
then saves the lines to the filename you specify.

It adds a '.py' extension to the file if you don't do so yourself, and
it asks for confirmation before overwriting existing files.

If `-r` option is used, the default extension is `.ipy`.

You'll want to use -r to use the raw input and the range of numbers are the numbers in the iPython shell, you can just do something like:

%save -r mysession 1-999999

And you'll get something like:

In [15]: %save -r mysession 1-99999
The following commands were written to file `mysession.ipy`:
Copy link

borosilicate commented Dec 3, 2019

When ever I'm trying to remember how to save in iPython... Thanks!

Copy link

awesomebytes commented Dec 3, 2019

@borosilicate Glad it was useful for you too!

Copy link

officialcjunior commented Mar 1, 2020

Thank you so much! :) 👍

Copy link

tahajalili commented Apr 11, 2020

Hey dude, thanks for your help!
I wanna know where does it save the file??

Copy link

awesomebytes commented Apr 11, 2020

Hey dude, thanks for your help!
I wanna know where does it save the file??

If you try it you'll see it saves to the current folder of the ipython shell

Copy link

k-bnet commented Apr 14, 2020

Thank youso much for a very useful info!

Copy link

Bwhiz commented May 3, 2020

How does one open a .ipy file directly from the ipython shell?

Copy link

ychaouche commented Oct 5, 2020

You forgot to mention that the second argument is mandatory

Copy link

coulid commented Jan 26, 2022

I am testing my code with ipython and rewriting in file the whole past month!!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment