diff options
author | Antoine Pitrou <solipsis@pitrou.net> | 2011-12-03 21:35:31 (GMT) |
---|---|---|
committer | Antoine Pitrou <solipsis@pitrou.net> | 2011-12-03 21:35:31 (GMT) |
commit | d4ddec59881802aa0c92b0736ff71eb6cff84857 (patch) | |
tree | eff9d94d1a76ddde32726bd37976473edbbf725e | |
parent | 48383bfc67438b0e280be732a13dbc77a8dceb8e (diff) | |
download | cpython-d4ddec59881802aa0c92b0736ff71eb6cff84857.zip cpython-d4ddec59881802aa0c92b0736ff71eb6cff84857.tar.gz cpython-d4ddec59881802aa0c92b0736ff71eb6cff84857.tar.bz2 |
Refine FAQ entry for catching stdout
-rw-r--r-- | Doc/faq/extending.rst | 21 |
1 files changed, 15 insertions, 6 deletions
diff --git a/Doc/faq/extending.rst b/Doc/faq/extending.rst index 676890e..7c684a0 100644 --- a/Doc/faq/extending.rst +++ b/Doc/faq/extending.rst @@ -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! |