[IPython-user] capture standard output (not Out[] variables) from embedded print statements in IPython?

Kenneth Arnold kenneth.arnold@gmail....
Mon Nov 9 18:07:56 CST 2009

It's unfortunate that this has to be a global setting. Common LISP has
a scoped with-output-to-string, which not only sets up everything for
you, but also avoids stepping on any other threads that might be
writing output (e.g., to some other string).

Googling reveals various shims that can go in sys.stdout. I can't
easily find a thread-safe one, but it should be not too hard to make
with thread-local storage.


On Mon, Nov 9, 2009 at 6:51 PM, Jon Olav Vik <jonovik@gmail.com> wrote:
> 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
> _______________________________________________
> IPython-user mailing list
> IPython-user@scipy.org
> http://mail.scipy.org/mailman/listinfo/ipython-user

More information about the IPython-user mailing list