target - The target, a file-like object where stdout should be redirected.
sys.stdout to file-like object .
May be useful for use with third-party code that uses only
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
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
# Into the line help_output.
out = io.StringIO ()
with redirect_stdout (out):
help_output = out.getvalue ()
# To a file on disk.
with open (’help.txt’,’ w’) as help_file:
with redirect_stdout (help_file):
# To stderr .
with redirect_stdout (sys.stderr):
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.