I am aware of: Redirect stdout to a file in Python?
I'm asking how to go about the following:
In [2]: with tempfile.NamedTemporaryFile() as tmp:
...: contextlib.redirect_stdout(tmp):
...: print('this')
Which errors with:
TypeError: a bytes-like object is required, not 'str'
From the docs (https://docs.python.org/3/library/contextlib.html#contextlib.redirect_stdout):
Context manager for temporarily redirecting sys.stdout to another file or file-like object.
Searching for which gave me this post: What is exactly a file-like object in Python? which states:
An object exposing a file-oriented API (with methods such as read() or write()) to an underlying resource
Which made me think perhaps the following would work:
In [2]: with tempfile.NamedTemporaryFile() as tmp:
...: contextlib.redirect_stdout(tmp.file):
...: print('this')
as tmp.file
has read
and write
from dir(tmp.file)
(so, is "file like" ? ).
This still errors though, with the same error message.
So, how should I go about redirecting standard out to a temporary file?