Rcjp's Weblog

March 24, 2009

Redirecting stdout within ipython

Filed under: python — rcjp @ 12:09 am

A friend was asking if I knew a way of grabbing the output from a python function within ipython. I couldn’t see an easy way (the normal shell way of ‘>’ redirection won’t work). So the following is a quick hack on IPython’s OutputTrap:

Sample session, just defining a function that outputs something and I’m also using the ipython trick of preceding the command with a comma to make the args into strings…

In [1]: def myfunc():
   ...:     print 'hello'

In [2]: run grab

In [3]: ,grab dumpfile myfunc()

and grab.py is…

import sys
from IPython import OutputTrap

def grab(fname, cmd):
    dump = OutputTrap.OutputTrap('dump','','',trap_out=1,quiet_out=1)
        eval(cmd, sys._getframe(1).f_globals, sys._getframe(1).f_locals)
        print sys.exc_info()

    file(fname,'w').writelines( dump.summary() )

… and the output of myfunc() appears in the file ‘dumpfile’ so it seems to work, but note I haven’t done much testing.



  1. nice work…

    Comment by ben — March 24, 2009 @ 10:12 am

  2. Sooooooo helpful. Thank you.

    Comment by Matt — June 7, 2009 @ 9:15 pm

  3. Neew IPython versions have this built in. Checkout %store magic function:


    Comment by Jakh Daven — May 24, 2011 @ 6:26 am

RSS feed for comments on this post.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: