Skip to content

Instantly share code, notes, and snippets.

@oyewunmio
Forked from awesomebytes/ipython_to_file.md
Created June 2, 2022 13:50
Show Gist options
  • Save oyewunmio/5e3e2a2546a90951f1ccd5286104c876 to your computer and use it in GitHub Desktop.
Save oyewunmio/5e3e2a2546a90951f1ccd5286104c876 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`:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment