[Python-checkins] cpython (3.2): Refine FAQ entry for catching stdout

antoine.pitrou python-checkins at python.org
Sat Dec 3 22:45:37 CET 2011


http://hg.python.org/cpython/rev/c82492fc9943
changeset:   73839:c82492fc9943
branch:      3.2
user:        Antoine Pitrou <solipsis at pitrou.net>
date:        Sat Dec 03 22:35:31 2011 +0100
summary:
  Refine FAQ entry for catching stdout

files:
  Doc/faq/extending.rst |  21 +++++++++++++++------
  1 files changed, 15 insertions(+), 6 deletions(-)


diff --git a/Doc/faq/extending.rst b/Doc/faq/extending.rst
--- a/Doc/faq/extending.rst
+++ b/Doc/faq/extending.rst
@@ -142,21 +142,30 @@
 just allow the standard traceback mechanism to work. Then, the output will go
 wherever your ``write()`` method sends it.
 
-The easiest way to do this is to use the StringIO class in the standard library.
+The easiest way to do this is to use the :class:`io.StringIO` class::
 
-Sample code and use for catching stdout:
+   >>> import io, sys
+   >>> sys.stdout = io.StringIO()
+   >>> print('foo')
+   >>> print('hello world!')
+   >>> sys.stderr.write(sys.stdout.getvalue())
+   foo
+   hello world!
 
-   >>> class StdoutCatcher:
+A custom object to do the same would look like this::
+
+   >>> import io, sys
+   >>> class StdoutCatcher(io.TextIOBase):
    ...     def __init__(self):
-   ...         self.data = ''
+   ...         self.data = []
    ...     def write(self, stuff):
-   ...         self.data = self.data + stuff
+   ...         self.data.append(stuff)
    ...
    >>> import sys
    >>> sys.stdout = StdoutCatcher()
    >>> print('foo')
    >>> print('hello world!')
-   >>> sys.stderr.write(sys.stdout.data)
+   >>> sys.stderr.write(''.join(sys.stdout.data))
    foo
    hello world!
 

-- 
Repository URL: http://hg.python.org/cpython


More information about the Python-checkins mailing list