Skip to content

Instantly share code, notes, and snippets.

@awesomebytes
Created March 16, 2016 10:38
Show Gist options
  • Star 48 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save awesomebytes/4972b76459822845cc71 to your computer and use it in GitHub Desktop.
Save awesomebytes/4972b76459822845cc71 to your computer and use it in GitHub Desktop.
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 CodeMagics.save of <IPython.core.magics.code.CodeMagics object at 0x7fb5d25bb1d0>>
Namespace:  IPython internal
File:       /usr/lib/python2.7/dist-packages/IPython/core/magics/code.py
Definition: %save(self, parameter_s='')
Docstring:
Save a set of lines or a macro to a given filename.

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

Options:

  -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`:
@Bwhiz
Copy link

Bwhiz commented May 3, 2020

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

@ychaouche
Copy link

You forgot to mention that the second argument is mandatory

@coulid
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