diff options
author | Raymond Hettinger <python@rcn.com> | 2013-10-10 00:46:57 -0700 |
---|---|---|
committer | Raymond Hettinger <python@rcn.com> | 2013-10-10 00:46:57 -0700 |
commit | 9103c0917e87ac4515b54a48dd4e8b8f1c514508 (patch) | |
tree | ab5c4b5bd6240dc21aefb4597d2653c560037dad /Doc/library/contextlib.rst | |
parent | ab93cc8ac7ecfd445f044145f33d8ae52cf4f304 (diff) | |
download | cpython-9103c0917e87ac4515b54a48dd4e8b8f1c514508.tar.gz |
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 349b805f3d..4b86755bad 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. |