ubelt.util_stream module¶
Functions for capturing and redirecting IO streams.
The CaptureStdout
captures all text sent to stdout and optionally
prevents it from actually reaching stdout.
The TeeStringIO
does the same thing but for arbitrary streams. It is
how the former is implemented.
- class ubelt.util_stream.TeeStringIO(redirect=None)[source]¶
Bases:
StringIO
An IO object that writes to itself and another IO stream.
- Variables
redirect (io.IOBase) – The other stream to write to.
Example
>>> import ubelt as ub >>> redirect = io.StringIO() >>> self = ub.TeeStringIO(redirect)
- isatty()[source]¶
Returns true of the redirect is a terminal.
Note
Needed for
IPython.embed
to work properly when this class is used to override stdout / stderr.
- fileno()[source]¶
Returns underlying file descriptor of the redirected IOBase object if one exists.
Example
>>> # Not sure the best way to test, this func is important for >>> # capturing stdout when ipython embedding >>> import pytest >>> with pytest.raises(io.UnsupportedOperation): >>> TeeStringIO(redirect=io.StringIO()).fileno() >>> with pytest.raises(io.UnsupportedOperation): >>> TeeStringIO(None).fileno()
- property encoding¶
Gets the encoding of the redirect IO object
Example
>>> import ubelt as ub >>> redirect = io.StringIO() >>> assert ub.TeeStringIO(redirect).encoding is None >>> assert ub.TeeStringIO(None).encoding is None >>> assert ub.TeeStringIO(sys.stdout).encoding is sys.stdout.encoding >>> redirect = io.TextIOWrapper(io.StringIO()) >>> assert ub.TeeStringIO(redirect).encoding is redirect.encoding
- class ubelt.util_stream.CaptureStdout(suppress=True, enabled=True)[source]¶
Bases:
CaptureStream
Context manager that captures stdout and stores it in an internal stream
- Parameters
suppress (bool, default=True) – if True, stdout is not printed while captured
enabled (bool, default=True) – does nothing if this is False
**kwargs – used for backwards compatibility with misspelled deprecated params.
- SeeAlso:
Example
>>> import ubelt as ub >>> self = ub.CaptureStdout(suppress=True) >>> print('dont capture the table flip (╯°□°)╯︵ ┻━┻') >>> with self: ... text = 'capture the heart ♥' ... print(text) >>> print('dont capture look of disapproval ಠ_ಠ') >>> assert isinstance(self.text, str) >>> assert self.text == text + '\n', 'failed capture text'
Example
>>> import ubelt as ub >>> self = ub.CaptureStdout(suppress=False) >>> with self: ... print('I am captured and printed in stdout') >>> assert self.text.strip() == 'I am captured and printed in stdout'
Example
>>> import ubelt as ub >>> self = ub.CaptureStdout(suppress=True, enabled=False) >>> with self: ... print('dont capture') >>> assert self.text is None