Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

Fix: add encoding, fileno to Stdout/Stderr (#639)

Akshay Agrawal77e0976332a7
diff --git a/marimo/_messaging/streams.py b/marimo/_messaging/streams.py
index 863c1d95d7..41c7df7d2f 100644
--- a/marimo/_messaging/streams.py
+++ b/marimo/_messaging/streams.py
@@ -1,6 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import contextlib
import io
import multiprocessing as mp
import os
@@ -9,7 +10,7 @@ import sys
import threading
from collections import deque
from multiprocessing.connection import Connection
-from typing import Any, Iterable, Optional
+from typing import Any, Iterable, Iterator, Optional
from marimo import _loggers
from marimo._ast.cell import CellId_t
@@ -80,12 +81,25 @@ class Stream:
LOGGER.debug("Error when writing (op: %s) to pipe: %s", op, e)
+# NB: Python doesn't provide a standard out class to inherit from, so
+# we inherit from TextIOBase.
class Stdout(io.TextIOBase):
name = "stdout"
+ encoding = sys.stdout.encoding
+ errors = sys.stdout.errors
+ _fileno: int | None = None
def __init__(self, stream: Stream):
self.stream = stream
+ def fileno(self) -> int:
+ if self._fileno is not None:
+ return self._fileno
+ raise io.UnsupportedOperation("Stream not redirected, no fileno.")
+
+ def _set_fileno(self, fileno: int | None) -> None:
+ self._fileno = fileno
+
def writable(self) -> bool:
return True
@@ -125,10 +139,21 @@ class Stdout(io.TextIOBase):
class Stderr(io.TextIOBase):
name = "stderr"
+ encoding = sys.stderr.encoding
+ errors = sys.stderr.errors
+ _fileno: int | None = None
def __init__(self, stream: Stream):
self.stream = stream
+ def fileno(self) -> int:
+ if self._fileno is not None:
+ return self._fileno
+ raise io.UnsupportedOperation("Stream not redirected, no fileno.")
+
+ def _set_fileno(self, fileno: int | None) -> None:
+ self._fileno = fileno
+
def writable(self) -> bool:
return True
@@ -173,10 +198,17 @@ class Stdin(io.TextIOBase):
"""Implements a subset of stdin."""
name = "stdin"
+ encoding = sys.stdin.encoding
+ errors = sys.stdin.errors
def __init__(self, stream: Stream):
self.stream = stream
+ def fileno(self) -> int:
+ raise io.UnsupportedOperation(
+ "marimo's stdin is a pseudofile, which has no fileno."
+ )
+
def writable(self) -> bool:
return False
@@ -221,3 +253,76 @@ class Stdin(io.TextIOBase):
# we don't support it.
del hint
return self._readline_with_prompt(prompt="").split("\n")
+
+
+def _forward_os_stream(stream_object: Stdout | Stderr, fd: int) -> None:
+ while True:
+ data = os.read(fd, 1024)
+ if not data:
+ break
+ stream_object.write(data.decode())
+
+
+def _dup2newfd(fd: int) -> tuple[int, int, int]:
+ """Create a pipe, with `fd` at the write end of it.
+
+ Returns
+ - duplicate (os.dup) of `fd`
+ - read end of pipe
+ - fd (which now points to the file referenced by the write end of the pipe)
+
+ When done with the pipe, the write-end of the pipe should be closed
+ and remapped to point to the saved duplicate. The read end should
+ also be closed, as should the saved duplicate.
+ """
+ # fd_dup keeps a pointer to `fd`'s original location
+ fd_dup = os.dup(fd)
+ # create a pipe, with `fd` as the write end of it
+ read_fd, write_fd = os.pipe()
+ # repurpose fd to point to the write-end of the pipe
+ os.dup2(write_fd, fd)
+ os.close(write_fd)
+ return fd_dup, read_fd, fd
+
+
+def _restore_fds(
+ fd_dup: int,
+ fd_read: int,
+ original_fd: int,
+ forwarding_thread: threading.Thread,
+) -> None:
+ # Restore the original file descriptors: point original_fd
+ # back to its original location. Before this call, original_fd
+ # is referring to the write end of a pipe. dup2 will
+ # close these fds before reusing them, which ensures that the
+ # forwarding threads will terminate.
+ os.dup2(fd_dup, original_fd)
+ forwarding_thread.join()
+ # Close since the original descriptor has been restored
+ os.close(fd_dup)
+ os.close(fd_read)
+
+
+def redirect(stream: Stdout | Stderr, fileno: int) -> Iterator[None]:
+ """Redirect fileno through the stream object."""
+ fd_dup, fd_read, fd = _dup2newfd(fileno)
+
+ # redirecting the standard streams in this way appears to have an overhead
+ # of ~1-2ms; the following alternatives had high variance, with up to 30ms
+ # overhead
+ # - reusing the same two threads instead of creating and destroying on
+ # each call; this requires (slow) synchronization with locks
+ # - using a multiprocessing ThreadPool
+ # - using a concurrent.futures.ThreadPool/ProcessPool
+ thread = threading.Thread(
+ target=_forward_os_stream, args=(stream, fd_read)
+ )
+ thread.start()
+
+ try:
+ stream._set_fileno(fd_dup)
+ yield
+ finally:
+ _restore_fds(fd_dup, fd_read, fd, thread)
+ stream._set_fileno(None)
diff --git a/marimo/_runtime/redirect_streams.py b/marimo/_runtime/redirect_streams.py
index e2c2ad360d..4be70d2ebe 100644
--- a/marimo/_runtime/redirect_streams.py
+++ b/marimo/_runtime/redirect_streams.py
@@ -4,11 +4,10 @@ from __future__ import annotations
import contextlib
import os
import sys
-import threading
from typing import Iterator
from marimo._ast.cell import CellId_t
-from marimo._messaging.streams import Stderr, Stdin, Stdout, Stream
+from marimo._messaging.streams import Stderr, Stdin, Stdout, Stream, redirect
def forward_os_stream(stream_object: Stdout | Stderr, fd: int) -> None:
@@ -58,26 +57,6 @@ def redirect_streams(
stream.cell_id = None
return
- # Redirect file descriptors for writable streams (stdout, stderr).
- #
- # All six of these file descriptors will need to be closed later
- stdout_duped, stdout_read_fd, stdout_fd = dup2newfd(sys.stdout.fileno())
- stderr_duped, stderr_read_fd, stderr_fd = dup2newfd(sys.stderr.fileno())
-
- # redirecting the standard streams in this way appears to have an overhead
- # of ~1-2ms; the following alternatives had high variance, with up to 30ms
- # overhead
- # - reusing the same two threads instead of creating and destroying on
- # each call; this requires (slow) synchronization with locks
- # - using a multiprocessing ThreadPool
- # - using a concurrent.futures.ThreadPool/ProcessPool
- stdout_thread = threading.Thread(
- target=forward_os_stream, args=(stdout, stdout_read_fd)
- )
- stderr_thread = threading.Thread(
- target=forward_os_stream, args=(stderr, stderr_read_fd)
- )
-
# NB: Python doesn't allow monkey patching methods builtins, so
# we replace these streams outright
py_stdout = sys.stdout
@@ -87,35 +66,11 @@ def redirect_streams(
sys.stderr = stderr # type: ignore
sys.stdin = stdin # type: ignore
- stdout_thread.start()
- stderr_thread.start()
-
- try:
+ with redirect(stdout, py_stdout.fileno()), redirect(
+ stderr, py_stderr.fileno()
+ ):
yield
- finally:
- # Restore the original std file descriptors: point stdout_fd and
- # stderr_fd to their original locations. Before this call, stdout_fd
- # and stderr_fd are referring to write ends of pipes. dup2 will
- # close these fds before reusing them, which ensures that the
- # forwarding stdout_thread and stderr_threads will terminate.
- os.dup2(stdout_duped, stdout_fd)
- os.dup2(stderr_duped, stderr_fd)
-
- stdout_thread.join()
- stderr_thread.join()
-
- # Close these descriptors, since the std file descriptors have been
- # restored.
- os.close(stdout_duped)
- os.close(stderr_duped)
-
- # Close the read ends of the pipes
- os.close(stdout_read_fd)
- os.close(stderr_read_fd)
-
- # Restore Python stdout/stderr/stdin
sys.stdout = py_stdout
sys.stderr = py_stderr
sys.stdin = py_stdin
-
stream.cell_id = None
diff --git a/tests/_messaging/test_streams.py b/tests/_messaging/test_streams.py
index 5c3f3cfda7..34fced7560 100644
--- a/tests/_messaging/test_streams.py
+++ b/tests/_messaging/test_streams.py
@@ -1,3 +1,5 @@
+import sys
+
from marimo._runtime.runtime import Kernel
from tests.conftest import ExecReqProvider, MockedKernel
@@ -5,6 +7,10 @@ from tests.conftest import ExecReqProvider, MockedKernel
# Make sure that standard in is installed; stdin is not writable so we
# just check that its methods are callable and return mocked values.
class TestStdin:
+ @staticmethod
+ def test_encoding(mocked_kernel: MockedKernel) -> None:
+ assert mocked_kernel.stdin.encoding == sys.stdin.encoding
+
@staticmethod
def test_input_installed(k: Kernel, exec_req: ExecReqProvider) -> None:
k.run([exec_req.get("output = input('hello')")])
@@ -22,6 +28,15 @@ class TestStdin:
class TestStdout:
+ @staticmethod
+ def test_encoding(mocked_kernel: MockedKernel) -> None:
+ assert mocked_kernel.stdout.encoding == sys.stdout.encoding
+
+ @staticmethod
+ def test_fileno(k: Kernel, exec_req: ExecReqProvider) -> None:
+ k.run([exec_req.get("fileno = sys.stdout.fileno()")])
+ assert k.globals["fileno"] is not None
+
@staticmethod
def test_print(
mocked_kernel: MockedKernel, exec_req: ExecReqProvider
@@ -53,6 +68,15 @@ class TestStdout:
class TestStderr:
+ @staticmethod
+ def test_encoding(mocked_kernel: MockedKernel) -> None:
+ assert mocked_kernel.stderr.encoding == sys.stderr.encoding
+
+ @staticmethod
+ def test_fileno(k: Kernel, exec_req: ExecReqProvider) -> None:
+ k.run([exec_req.get("fileno = sys.stderr.fileno()")])
+ assert k.globals["fileno"] is not None
+
@staticmethod
def test_write(
mocked_kernel: MockedKernel, exec_req: ExecReqProvider
diff --git a/tests/conftest.py b/tests/conftest.py
index dd5dc7d121..3fbf950bcb 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -29,32 +29,39 @@ class _MockStream:
self.messages.append((op, data))
class MockStdout(Stdout):
"""Captures the output sent through the stream"""
- messages: list[str] = dataclasses.field(default_factory=list)
+ def __init__(self, stream: _MockStream) -> None:
+ super().__init__(stream)
+ self.messages: list[str] = []
def write(self, data: str) -> int:
self.messages.append(data)
return len(data)
class MockStderr(Stderr):
"""Captures the output sent through the stream"""
messages: list[str] = dataclasses.field(default_factory=list)
+ def __init__(self, stream: _MockStream) -> None:
+ super().__init__(stream)
+ self.messages: list[str] = []
+
def write(self, data: str) -> int:
self.messages.append(data)
return len(data)
class MockStdin(Stdin):
"""Echoes the prompt."""
+ def __init__(self, stream: _MockStream) -> None:
+ super().__init__(stream)
+ self.messages: list[str] = []
+
def _readline_with_prompt(self, prompt: str = "") -> str:
return prompt
@@ -62,11 +69,12 @@ class MockStdin(Stdin):
@dataclasses.dataclass
class MockedKernel:
stream: _MockStream = dataclasses.field(default_factory=_MockStream)
- stdout: MockStdout = dataclasses.field(default_factory=MockStdout)
- stderr: MockStderr = dataclasses.field(default_factory=MockStderr)
- stdin: MockStdin = dataclasses.field(default_factory=MockStdin)
def __post_init__(self) -> None:
+ self.stdout = MockStdout(self.stream)
+ self.stderr = MockStderr(self.stream)
+ self.stdin = MockStdin(self.stream)
+
self.k = Kernel(
stream=self.stream,
stdout=self.stdout,