Merge pull request #1870 from minrk/captureio

New `%%capture` cell magic captures stdout/err while running a cell.

Uses `capture_output()` context manager, moved to utils.io from IPython.parallel testing utilities, where it originated.

The caputre objects can be printed as a string, case in which they display the captured stdout, which is also available as `.stdout`.  The captured stderr, if any, is in a `.stderr` attribute.  A `.show()` method can be called to quickly print both, with stderr being correctly printed to the sys.stderr stream (so the notebook displays it with red highlighting).

closes #1863
Fernando Perez 14 years ago
commit 4251457d9a

@ -20,7 +20,7 @@ from subprocess import Popen, PIPE
import nose.tools as nt
from IPython.testing import decorators as dec
from IPython.utils.io import Tee
from IPython.utils.io import Tee, capture_output
from IPython.utils.py3compat import doctest_refactor_print
#-----------------------------------------------------------------------------
@ -73,3 +73,13 @@ def test_io_init():
# __class__ is a reference to the class object in Python 3, so we can't
# just test for string equality.
assert 'IPython.utils.io.IOStream' in classname, classname
def test_capture_output():
"""capture_output() context works"""
with capture_output() as io:
print 'hi, stdout'
print >> sys.stderr, 'hi, stderr'
nt.assert_equals(io.stdout, 'hi, stdout\n')
nt.assert_equals(io.stderr, 'hi, stderr\n')

Loading…
Cancel
Save