0

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?

baxx
  • 3,956
  • 6
  • 37
  • 75
  • You're missing a `with` before `contextlib.redirect_stdout(tmp)`. So `with contextlib.redirect_stdout(tmp): ...` – aneroid Apr 25 '21 at 12:00

1 Answers1

1

This way, it seems to work:

with tempfile.NamedTemporaryFile(mode='w') as tmp:
    with contextlib.redirect_stdout(tmp):
        print('this')

NB: the default value for 'mode' is 'w+b'

XtianP
  • 389
  • 2
  • 5