contextlib.redirect_stdout (target)
target - The target, a file-like object where stdout should be redirected.
Will redirect sys.stdout
to file-like object .
May be useful for use with third-party code that uses only stdout
.
Note
From- because of the "global" nature of sys.stdout
, you should not use this manager in library code and in the vast majority of threaded programs. Also, it doesn’t work with subprocess output (see subprocess
).
The example below help () uses
sys.stdout
, but with of the manager in question, you can redirect the output to io.StringIO
, to a file on disk, or to sys.stderr
: # Into the line help_output.
out = io.StringIO ()
with redirect_stdout (out):
help (pow)
help_output = out.getvalue ()
# To a file on disk.
with open (’help.txt’,’ w’) as help_file:
with redirect_stdout (help_file):
help (pow)
# To stderr .
with redirect_stdout (sys.stderr):
help (pow)
Notes
The created object manager is reentrant . This means that within a single with
block that has the same nested blocks, it can be used multiple times.