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)
    dump.trap_all()
    try:
        eval(cmd, sys._getframe(1).f_globals, sys._getframe(1).f_locals)
    except:
        print sys.exc_info()

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

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

2 Comments »

  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


RSS feed for comments on this post.

Leave a comment

Blog at WordPress.com.