Skip to content

StreamCapture

Base classes

Name Children Inherits
StringIO
_io
Text I/O implementation using an in-memory buffer.
  • _TextIOBase

⋔ Inheritance diagram

graph TD
  3080145239["utils.StreamCapture"]
  881058128["_io.StringIO"]
  1847852277["_io._TextIOBase"]
  2763917956["_io._IOBase"]
  2751680898["builtins.object"]
  881058128 --> 3080145239
  1847852277 --> 881058128
  2763917956 --> 1847852277
  2751680898 --> 2763917956

🛈 DocStrings

Bases: StringIO

Capture and forward output to a queue.

Writes from other threads (sync code run via asyncio.to_thread) are handed to the event loop the capture was created on: asyncio queues are not thread-safe. The redirect this is used with (contextlib.redirect_stdout) is process-global, so output of other tasks and threads during a run is captured too.

Source code in src/exxec/local_provider/utils.py
class StreamCapture(io.StringIO):
    """Capture and forward output to a queue.

    Writes from other threads (sync code run via `asyncio.to_thread`) are handed to
    the event loop the capture was created on: asyncio queues are not thread-safe.
    The redirect this is used with (`contextlib.redirect_stdout`) is process-global,
    so output of other tasks and threads during a run is captured too.
    """

    def __init__(self, original_stream: TextIO, queue: asyncio.Queue[str]) -> None:
        super().__init__()
        self.original_stream = original_stream
        self.queue = queue
        try:
            self._loop: asyncio.AbstractEventLoop | None = asyncio.get_running_loop()
        except RuntimeError:
            self._loop = None
        self._loop_thread = threading.get_ident()

    def _put(self, line: str) -> None:
        with contextlib.suppress(asyncio.QueueFull):
            self.queue.put_nowait(line)

    def write[S: (str, bytes)](self, s: S) -> int:
        """Capture and forward output to a queue."""
        text = s if isinstance(s, str) else s.decode()
        result = self.original_stream.write(text)
        if text:
            lines = text.splitlines(keepends=True)
            for line in lines:
                if not line.strip():
                    continue
                if self._loop is None or threading.get_ident() == self._loop_thread:
                    self._put(line.rstrip("\n\r"))
                else:
                    with contextlib.suppress(RuntimeError):  # loop already closed
                        self._loop.call_soon_threadsafe(self._put, line.rstrip("\n\r"))
        return result

    def flush(self) -> None:
        """Flush the stream."""
        return self.original_stream.flush()

flush

flush() -> None

Flush the stream.

Source code in src/exxec/local_provider/utils.py
def flush(self) -> None:
    """Flush the stream."""
    return self.original_stream.flush()

write

write(s: S) -> int

Capture and forward output to a queue.

Source code in src/exxec/local_provider/utils.py
def write[S: (str, bytes)](self, s: S) -> int:
    """Capture and forward output to a queue."""
    text = s if isinstance(s, str) else s.decode()
    result = self.original_stream.write(text)
    if text:
        lines = text.splitlines(keepends=True)
        for line in lines:
            if not line.strip():
                continue
            if self._loop is None or threading.get_ident() == self._loop_thread:
                self._put(line.rstrip("\n\r"))
            else:
                with contextlib.suppress(RuntimeError):  # loop already closed
                    self._loop.call_soon_threadsafe(self._put, line.rstrip("\n\r"))
    return result

:fa-brands-github: Show source on GitHub