Capturing Output with %%capture¶
One of IPython's new cell magics is %%capture
, which captures stdout/err for a cell,
and discards them or stores them in variables in your namespace.
import sys
By default, it just swallows it up. This is a simple way to suppress unwanted output.
%%capture
print 'hi, stdout'
print >> sys.stderr, 'hi, stderr'
If you specify a name, then stdout and stderr will be stored in an object in your namespace.
%%capture captured
print 'hi, stdout'
print >> sys.stderr, 'hi, stderr'
captured
Calling the object writes the output to stdout/err as appropriate.
captured()
captured.stdout
captured.stderr
%%capture
only captures stdout/err, not displaypub, so you can still do plots and use the display protocol inside %%capture
%pylab inline
%%capture wontshutup
print "setting up X"
x = np.linspace(0,5,1000)
print "step 2: constructing y-data"
y = np.sin(x)
print "step 3: display info about y"
plt.plot(x,y)
print "okay, I'm done now"
wontshutup()
And you can selectively disable capturing stdout or stderr by passing --no-stdout/err
.
%%capture cap --no-stderr
print 'hi, stdout'
print >> sys.stderr, "hello, stderr"
cap.stdout
cap.stderr