]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
Refine FAQ entry for catching stdout
authorAntoine Pitrou <solipsis@pitrou.net>
Sat, 3 Dec 2011 21:35:31 +0000 (22:35 +0100)
committerAntoine Pitrou <solipsis@pitrou.net>
Sat, 3 Dec 2011 21:35:31 +0000 (22:35 +0100)
Doc/faq/extending.rst

index 676890e27c57ec503a04d79b2a191895482da098..7c684a092948ed32366ec57f4e8fe8f97f32d741 100644 (file)
@@ -142,21 +142,30 @@ this object to :data:`sys.stdout` and :data:`sys.stderr`.  Call print_error, or
 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!
+
+A custom object to do the same would look like this::
 
-   >>> class StdoutCatcher:
+   >>> 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!