redirect_stderr
ClassPrivateContextSource
with redirect_stderr(target: SupportsWrite):
...
A wrapped version of contextlib.redirect_stderr.
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 stdout.
Aliases
This class can be acquired by
import syncstream
syncstream.redirect_stderr
syncstream.base.redirect_stderr
Arguments
| Argument | Type | Required | |
|---|---|---|---|
target | SupportsWrite | A writable buffer supporting the write method. |
Example
Redirect stderr to buffer
- Codes
- Better codes
- Results
use_this_function.py
import syncstream
from syncstream.base import redirect_stderr
buffer = syncstream.LineBuffer(10)
with redirect_stderr(buffer):
try:
raise TypeError("test-error!")
except Exception as exc:
print(exc, file=buffer)
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.
try:
raise TypeError("test-error!")
except Exception as exc:
print(exc, file=buffer)
messages = buffer.read()
for mitem in messages:
print(mitem)
test-error!