redirect_stdout
ClassPrivateContextSource
with redirect_stdout(target: SupportsWrite):
...
A wrapped version of contextlib.redirect_stdout.
This context allows a syncstream.LineBuffer or its mirror to be configured as
the redirect target without raising typehint errors.
tip
You do not need to use this context because a buffer like LineBuffer is already a context now.
Because the buffer context will make both stdout and stderr redirected, you may want to use this context if you do not want to redirect stderr.
Aliases
This class can be acquired by
import syncstream
syncstream.redirect_stdout
syncstream.base.redirect_stdout
Arguments
| Argument | Type | Required | |
|---|---|---|---|
target | SupportsWrite | A writable buffer supporting the write method. |
Example
Redirect stdout to buffer
- Codes
- Better codes
- Results
use_this_function.py
import syncstream
from syncstream.base import redirect_stdout
buffer = syncstream.LineBuffer(10)
with redirect_stdout(buffer):
for i in range(20):
print(f'Message "{i:02d}".')
print('No line break.', end='')
messages = buffer.read()
for mitem in messages:
print(mitem)
use_buffer_context_directly.py
import syncstream
buffer = syncstream.LineBuffer(10)
with buffer: # Both the stdout and stderr are catched.
for i in range(20):
print(f'Message "{i:02d}".')
print('No line break.', end='')
messages = buffer.read()
for mitem in messages:
print(mitem)
Message "11".
Message "12".
Message "13".
Message "14".
Message "15".
Message "16".
Message "17".
Message "18".
Message "19".
No line break.