[IPython-user] capture standard output (not Out[] variables) from embedded print statements in IPython?
Jon Olav Vik
jonovik@gmail....
Mon Nov 9 17:51:24 CST 2009
Reckoner <reckoner <at> gmail.com> writes:
> I am aware of %logstart, but what if I want to capture the results of
> 'print' statements within my code that don't generate corresponding
> Out[] variables which would otherwise be caught with %logstart, etc.
Could you give a specific example? If your problem is a piece of code outside
your control, that prints important information to standard output instead of
returning it as a function result, you could perhaps redefine sys.stdout to a
StringIO file.
http://docs.python.org/library/sys.html
http://docs.python.org/library/stringio.html
In [51]: %doctest_mode
*** Pasting of code with ">>>" or "..." has been enabled.
Exception reporting mode: Plain
Doctest mode is: ON
>>> def fun():
... print "Printed to standard output"
... return "Returned as function value"
...
>>> fun()
Printed to standard output
'Returned as function value'
>>> import sys
>>> import StringIO
>>> stringio = StringIO.StringIO()
>>> sys.stdout = stringio
fun() # look Ma, no >>> prompt!
'Returned as function value'
sys.stdout = sys.__stdout__ # restore original stdout
>>> print stringio.getvalue()
☺←[0;32m☻>>> ☺←[0m☻Printed to standard output
☺←[0;32m☻>>> ☺←[0m☻
Note that the contents of stringio.getvalue() contains the suppressed >>>
prompts (plus something I suspect is color control characters...)
Hope this helps,
Jon Olav
More information about the IPython-user
mailing list