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.
nice work…
Comment by ben — March 24, 2009 @ 10:12 am
Sooooooo helpful. Thank you.
Comment by Matt — June 7, 2009 @ 9:15 pm
Neew IPython versions have this built in. Checkout %store magic function:
http://ipython.scipy.org/doc/rel-0.9.1/html/interactive/reference.html
Comment by Jakh Daven — May 24, 2011 @ 6:26 am