Tuesday, July 10, 2012

IPython: How to save code entered in the shell to a file

If you have done any serious development in IPython, you would have struggled joggling between the IPython shell and the editor (vim).

Wouldn't it be ideal if you wrote a function/class definition and you want to write that into your source code file?

The magic function '%save' does that but it overwrites the target file at every call.

Here is a neat little function you can use to save any function/class that you have written/tested in IPython to your source code file:

def s(startline, endline=None):
    if endline:
        for i in range(startline, endline):
            s(i)
    else:
        f = open('/tmp/t', 'a')
        l = eval('_i%s' % startline)
        f.write(l)
        f.close()

How do you use this?
Well, when you enter a function/class definition in the IPython shell, they are preceded by a line number. Just call this function with the line number and it will save it to the /tmp/t file.


As can be surmised from the code, you may use a line number range as well.

The magic: _i is a special variable used by IPython. _i<line number> refers to the line of code you entered. All this code does is save it to a file. 

Hope this makes IPython development easier!

[Update:13th July 2012] - This is now going to be part of IPython!
[Update:16th July 2012] - Change has now been merged - IPython's %save -a will now append to a file.

3 comments:

  1. Entering functions line-by-line in IPython is a bit tedious, even with vi-mode enabled in one's .inputrc - which is why most of the time I write my function directly in a vim-buffer and then ship it to IPython using vim-ipython.

    In fact, with the vim-ipython 'shell' enabled, even if you do happen to enter a function or a class definition from some other client, it will show up in your vim-ipython buffer, so you can just delete the leading "In[..]:" part and copy it elsewhere.

    There are links to demo screencasts from the GitHub page, and IPython 0.11 or higher is required.

    ReplyDelete