ubelt.util_stream module

Functions for capturing and redirecting IO streams.

class ubelt.util_stream.TeeStringIO(redirect=None)[source]

Bases: _io.StringIO

An IO object that writes to itself and another IO stream.

Variables:redirect (io.IOBase) – The other stream to write to.

Example

>>> redirect = io.StringIO()
>>> self = TeeStringIO(redirect)
isatty()[source]

Returns true of the redirect is a terminal.

Notes

Needed for IPython.embed to work properly when this class is used to override stdout / stderr.

encoding

Gets the encoding of the redirect IO object

Doctest:
>>> redirect = io.StringIO()
>>> assert TeeStringIO(redirect).encoding is None
>>> assert TeeStringIO(None).encoding is None
>>> assert TeeStringIO(sys.stdout).encoding is sys.stdout.encoding
>>> redirect = io.TextIOWrapper(io.StringIO())
>>> assert TeeStringIO(redirect).encoding is redirect.encoding
write(msg)[source]

Write to this and the redirected stream

flush()[source]

Flush to this and the redirected stream

class ubelt.util_stream.CaptureStream[source]

Bases: object

Generic class for capturing streaming output from stdout or stderr

class ubelt.util_stream.CaptureStdout(supress=True, enabled=True)[source]

Bases: ubelt.util_stream.CaptureStream

Context manager that captures stdout and stores it in an internal stream

Parameters:
  • supress (bool, default=True) – if True, stdout is not printed while captured
  • enabled (bool, default=True) – does nothing if this is False

Example

>>> self = CaptureStdout(supress=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, six.text_type)
>>> assert self.text == text + '\n', 'failed capture text'

Example

>>> self = CaptureStdout(supress=False)
>>> with self:
...     print('I am captured and printed in stdout')
>>> assert self.text.strip() == 'I am captured and printed in stdout'

Example

>>> self = CaptureStdout(supress=True, enabled=False)
>>> with self:
...     print('dont capture')
>>> assert self.text is None
log_part()[source]

Log what has been captured so far

start()[source]
stop()[source]
Doctest:
>>> CaptureStdout(enabled=False).stop()
>>> CaptureStdout(enabled=True).stop()
close()[source]