diff options
author | Raymond Hettinger <python@rcn.com> | 2013-10-10 07:46:57 (GMT) |
---|---|---|
committer | Raymond Hettinger <python@rcn.com> | 2013-10-10 07:46:57 (GMT) |
commit | 088cbf2d390f6caeb021f05909e1d0b2e506b332 (patch) | |
tree | 0e89ef127f2bdec4e01aa001b23bf6af2ff140b6 /Doc/library/contextlib.rst | |
parent | 5ed3bc9adbb5af56450b918410bf07b2bf54ef54 (diff) | |
download | cpython-088cbf2d390f6caeb021f05909e1d0b2e506b332.zip cpython-088cbf2d390f6caeb021f05909e1d0b2e506b332.tar.gz cpython-088cbf2d390f6caeb021f05909e1d0b2e506b332.tar.bz2 |
Issue #15805: Add contextlib.redirect_stdout()
Diffstat (limited to 'Doc/library/contextlib.rst')
-rw-r--r-- | Doc/library/contextlib.rst | 31 |
1 files changed, 31 insertions, 0 deletions
diff --git a/Doc/library/contextlib.rst b/Doc/library/contextlib.rst index 349b805..4b86755 100644 --- a/Doc/library/contextlib.rst +++ b/Doc/library/contextlib.rst @@ -115,6 +115,37 @@ Functions and classes provided: .. versionadded:: 3.4 +.. function:: redirect_stdout(new_target) + + Context manager for temporarily redirecting :data:`sys.stdout` to + another file or file-like object. + + This tool adds flexibility to existing functions or classes whose output + is hardwired to stdout. + + For example, the output of :func:`help` normally is sent to *sys.stdout*. + You can capture that output in a string by redirecting the output to a + :class:`io.StringIO` object:: + + f = io.StringIO() + with redirect_stdout(f): + help(pow) + s = f.getvalue() + + To send the output of :func:`help` to a file on disk, redirect the output + to a regular file:: + + with open('help.txt', 'w') as f: + with redirect_stdout(f): + help(pow) + + To send the output of :func:`help` to *sys.stderr*:: + + with redirect_stdout(sys.stderr): + help(pow) + + .. versionadded:: 3.4 + .. class:: ContextDecorator() A base class that enables a context manager to also be used as a decorator. |