##// END OF EJS Templates
Merge pull request #2179 from dopplershift/pylab-switch...
Merge pull request #2179 from dopplershift/pylab-switch Enable switching %pylab mode between inline and a single gui mode in a single notebook. With this merge, `%pylab` can be called interactively to toggle inline/GUI (matplotlib floating windows) mode. After initializing `%pylab inline`, now one can call `%pylab` without arguments to activate the default GUI or ask for a specific one as usual. IPython will detect if a different GUI is requested if one was already activated and will refuse to do so (to prevent multiple event loops from running concurrently, which often leads to problems).

File last commit:

r7739:dff285da
r8027:6dac6929 merge
Show More
Capturing Output.ipynb
208 lines | 4.2 KiB | text/plain | TextLexer

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.

In [ ]:
import sys

By default, it just swallows it up. This is a simple way to suppress unwanted output.

In [ ]:
%%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.

In [ ]:
%%capture captured
print 'hi, stdout'
print >> sys.stderr, 'hi, stderr'
In [ ]:
captured

Calling the object writes the output to stdout/err as appropriate.

In [ ]:
captured()
In [ ]:
captured.stdout
In [ ]:
captured.stderr

%%capture only captures stdout/err, not displaypub, so you can still do plots and use the display protocol inside %%capture

In [ ]:
%pylab inline
In [ ]:
%%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"
In [ ]:
wontshutup()

And you can selectively disable capturing stdout or stderr by passing --no-stdout/err.

In [ ]:
%%capture cap --no-stderr
print 'hi, stdout'
print >> sys.stderr, "hello, stderr"
In [ ]:
cap.stdout
In [ ]:
cap.stderr