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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: capture stdout and stderr utilities (#169)
Akshay Agrawald2415b68c3f6
diff --git a/docs/api/console.md b/docs/api/console.mdnew file mode 100644index 0000000000..f7104b58d4--- /dev/null+++ b/docs/api/console.md@@ -0,0 +1,24 @@+# Console outputs++Outputs written to `stdout` or `stderr`, including print statements+and logs, show up in a console output area below a cell.++By default, these console outputs don't appear when running a marimo notebook+as an app. If you do want them to appear in apps, marimo provides utility+functions for capturing console outputs and redirecting them to cell outputs.++```{eval-rst}+.. autofunction:: marimo.redirect_stdout+```++```{eval-rst}+.. autofunction:: marimo.redirect_stderr+```++```{eval-rst}+.. autofunction:: marimo.capture_stdout+```++```{eval-rst}+.. autofunction:: marimo.capture_stderr+```diff --git a/docs/api/index.md b/docs/api/index.mdindex fe88359def..37accf0bed 100644--- a/docs/api/index.md+++ b/docs/api/index.md@@ -11,16 +11,19 @@plottingmedia/indexhtml+ consolecontrol_flowstatedebugging```-Use the marimo library in marimo notebooks (`import marimo as mo`) to connect-interactive components like sliders, dropdowns, and tables to Python, layout-information with tabs or grids, output media like images and audio, express-yourself with dynamically created markdown (parametrized by Python values!),-and more.+Use the marimo library in marimo notebooks (`import marimo as mo`) to++- connect interactive inputs like sliders, dropdowns, and tables to Python,+- express yourself with dynamically created markdown,+- layout information with tabs or grids,+- output media like images and audio,+- and more!| | || :------------------- | :-------------------------------------------------------- |@@ -30,6 +33,7 @@ and more.| {doc}`plotting` | Output interactive plots || {doc}`media/index` | Output media like images, audio, PDFs, and plain text || {doc}`html` | Manipulate HTML objects |+| {doc}`console` | Redirect print statements and other console output || {doc}`control_flow` | Control how cells execute || {doc}`state` | Make stateful apps with `mo.state` || {doc}`debugging` | Debugging utilities |diff --git a/marimo/__init__.py b/marimo/__init__.pyindex caee3aa7fd..02cbc2e248 100644--- a/marimo/__init__.py+++ b/marimo/__init__.py@@ -19,6 +19,8 @@ __all__ = ["as_html","audio","callout",+ "capture_stdout",+ "capture_stderr","center","defs","doc",@@ -32,6 +34,8 @@ __all__ = ["output","plain_text","pdf",+ "redirect_stderr",+ "redirect_stdout","refs","right","state",@@ -62,6 +66,12 @@ from marimo._plugins.stateless.plain_text import plain_textfrom marimo._plugins.stateless.tabs import tabsfrom marimo._plugins.stateless.tree import treefrom marimo._runtime import output+from marimo._runtime.capture import (+ capture_stderr,+ capture_stdout,+ redirect_stderr,+ redirect_stdout,+)from marimo._runtime.control_flow import MarimoStopError, stopfrom marimo._runtime.runtime import defs, refsfrom marimo._runtime.state import statediff --git a/marimo/_messaging/streams.py b/marimo/_messaging/streams.pyindex b04ed60d75..ebcdebcf46 100644--- a/marimo/_messaging/streams.py+++ b/marimo/_messaging/streams.py@@ -1,17 +1,14 @@# Copyright 2023 Marimo. All rights reserved.from __future__ import annotations-import contextlib-import osimport sysimport threadingfrom collections import dequefrom multiprocessing.connection import Connection-from typing import Any, Iterator, Optional+from typing import Any, Optionalfrom marimo._ast.cell import CellId_tfrom marimo._messaging.console_output_worker import ConsoleMsg, buffered_writer-from marimo._runtime.context import get_context# Byte limits on outputs. Limits exist for two reasons:#@@ -133,101 +130,3 @@ class Stderr:def seekable(self) -> bool:return False---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---# Redirect stdout/stderr, if they have been installed-def redirect_streams(cell_id: CellId_t) -> Iterator[None]:- ctx = get_context()- ctx.stream.cell_id = cell_id- if ctx.stdout is None or ctx.stderr is None:- try:- yield- finally:- ctx.stream.cell_id = None- return-- # 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=(ctx.stdout, stdout_read_fd)- )- stderr_thread = threading.Thread(- target=forward_os_stream, args=(ctx.stderr, stderr_read_fd)- )-- py_stdout = sys.stdout- py_stderr = sys.stderr- sys.stdout = ctx.stdout # type: ignore- sys.stderr = ctx.stderr # type: ignore-- stdout_thread.start()- stderr_thread.start()-- try:- 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- sys.stdout = py_stdout- sys.stderr = py_stderr-- ctx.stream.cell_id = Nonediff --git a/marimo/_runtime/capture.py b/marimo/_runtime/capture.pynew file mode 100644index 0000000000..f6fb96ea81--- /dev/null+++ b/marimo/_runtime/capture.py@@ -0,0 +1,87 @@+# Copyright 2023 Marimo. All rights reserved.+import contextlib+import io+import sys+from typing import Iterator++from marimo._plugins.stateless.plain_text import plain_text+from marimo._runtime.output import _output+++def capture_stdout() -> Iterator[io.StringIO]:+ """Capture standard output.++ Use this context manager to capture print statements and+ other output sent to standard output.++ **Example.**++ ```python+ with mo.capture_stdout() as buffer:+ print("Hello!")+ output = buffer.getvalue()+ ```+ """+ with contextlib.redirect_stdout(io.StringIO()) as buffer:+ yield buffer+++def capture_stderr() -> Iterator[io.StringIO]:+ """Capture standard error.++ Use this context manager to capture output sent to standard error.++ **Example.**++ ```python+ with mo.capture_stderr() as buffer:+ sys.stderr.write("Hello!")+ output = buffer.getvalue()+ ```+ """+ with contextlib.redirect_stderr(io.StringIO()) as buffer:+ yield buffer+++def _redirect(msg: str) -> None:+ _output.append(plain_text(msg))+++def redirect_stdout() -> Iterator[None]:+ """Redirect stdout to a cell's output area.++ ```python+ with mo.redirect_stdout():+ # These print statements will show up in the cell's output area+ print("Hello!")+ print("World!")+ ```+ """+ old_stdout_write = sys.stdout.write+ sys.stdout.write = _redirect # type: ignore+ try:+ yield+ finally:+ sys.stdout.write = old_stdout_write # type: ignore+++def redirect_stderr() -> Iterator[None]:+ """Redirect `stderr` to a cell's output area.++ ```python+ with mo.redirect_stdout():+ # These messages will show up in the cell's output area+ sys.stderr.write("Hello!")+ sys.stderr.write("World!")+ ```+ """+ old_stderr_write = sys.stderr.write+ sys.stderr.write = _redirect # type: ignore+ try:+ yield+ finally:+ sys.stderr.write = old_stderr_write # type: ignorediff --git a/marimo/_runtime/conftest.py b/marimo/_runtime/conftest.pyindex 3965d6c7b0..1ed1fa53b7 100644--- a/marimo/_runtime/conftest.py+++ b/marimo/_runtime/conftest.py@@ -1,6 +1,7 @@# Copyright 2023 Marimo. All rights reserved.from __future__ import annotations+import dataclassesimport textwrapfrom typing import Any, Generator@@ -14,26 +15,59 @@ from marimo._runtime.requests import ExecutionRequestfrom marimo._runtime.runtime import Kernelclass _MockStream:+ messages: list[tuple[str, dict[Any, Any]]] = dataclasses.field(+ default_factory=list+ )+def write(self, op: str, data: dict[Any, Any]) -> None:- del op- del data- pass+ self.messages.append((op, data))+++class _MockStdStream:+ messages: list[str] = dataclasses.field(default_factory=list)++ def write(self, msg: str) -> None:+ self.messages.append(msg)+++class MockedKernel:+ k: Kernel = dataclasses.field(default_factory=Kernel)+ stream: _MockStream = dataclasses.field(default_factory=_MockStream)+ stdout: _MockStdStream = dataclasses.field(default_factory=_MockStdStream)+ stderr: _MockStdStream = dataclasses.field(default_factory=_MockStdStream)++ def __post_init__(self) -> None:+ get_context().initialize(+ kernel=self.k,+ ui_element_registry=UIElementRegistry(),+ interactive_mpl_registry=InteractiveMplRegistry(),+ stream=self.stream, # type: ignore+ stdout=self.stdout, # type: ignore+ stderr=self.stderr, # type: ignore+ )# fixture that provides a kernel (and tears it down)@pytest.fixturedef k() -> Generator[Kernel, None, None]:- k = Kernel()- get_context().initialize(- kernel=k,- ui_element_registry=UIElementRegistry(),- interactive_mpl_registry=InteractiveMplRegistry(),- stream=_MockStream(), # type: ignore- stdout=None,- stderr=None,- )- yield k+ mocked = MockedKernel()+ yield mocked.k+ # have to teardown the runtime context because it's a global+ get_context()._kernel = None+ get_context()._ui_element_registry = None+ get_context()._stream = None+ get_context()._initialized = False+++# fixture that wraps a kernel and other mocked objects+def mocked_kernel() -> Generator[MockedKernel, None, None]:+ mocked = MockedKernel()+ yield mocked# have to teardown the runtime context because it's a globalget_context()._kernel = Noneget_context()._ui_element_registry = Nonediff --git a/marimo/_runtime/redirect_streams.py b/marimo/_runtime/redirect_streams.pynew file mode 100644index 0000000000..1476da982a--- /dev/null+++ b/marimo/_runtime/redirect_streams.py@@ -0,0 +1,110 @@+# Copyright 2023 Marimo. All rights reserved.+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, Stdout+from marimo._runtime.context import get_context+++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+++# Redirect stdout/stderr, if they have been installed+def redirect_streams(cell_id: CellId_t) -> Iterator[None]:+ ctx = get_context()+ ctx.stream.cell_id = cell_id+ if ctx.stdout is None or ctx.stderr is None:+ try:+ yield+ finally:+ ctx.stream.cell_id = None+ return++ # 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=(ctx.stdout, stdout_read_fd)+ )+ stderr_thread = threading.Thread(+ target=forward_os_stream, args=(ctx.stderr, stderr_read_fd)+ )++ py_stdout = sys.stdout+ py_stderr = sys.stderr+ sys.stdout = ctx.stdout # type: ignore+ sys.stderr = ctx.stderr # type: ignore++ stdout_thread.start()+ stderr_thread.start()++ try:+ 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+ sys.stdout = py_stdout+ sys.stderr = py_stderr++ ctx.stream.cell_id = Nonediff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 5f375ba485..9c3a2c7a8a 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -37,7 +37,7 @@ from marimo._messaging.ops import (VariableValue,VariableValues,)-from marimo._messaging.streams import Stderr, Stdout, Stream, redirect_streams+from marimo._messaging.streams import Stderr, Stdout, Streamfrom marimo._output import formattingfrom marimo._output.rich_help import mddocfrom marimo._plugins.stateless.mpl._mpl import InteractiveMplRegistry@@ -51,6 +51,7 @@ from marimo._runtime.context import (initialize_context,)from marimo._runtime.control_flow import MarimoInterrupt, MarimoStopError+from marimo._runtime.redirect_streams import redirect_streamsfrom marimo._runtime.requests import (CompletionRequest,ConfigurationRequest,diff --git a/marimo/_runtime/test_capture.py b/marimo/_runtime/test_capture.pynew file mode 100644index 0000000000..78c2e2d07e--- /dev/null+++ b/marimo/_runtime/test_capture.py@@ -0,0 +1,155 @@+# Copyright 2023 Marimo. All rights reserved.+from __future__ import annotations++import re+from typing import Any, Dict, Tuple++from marimo._runtime.conftest import ExecReqProvider, MockedKernel+++def _has_output(+ messages: list[Tuple[str, Dict[Any, Any]]], pattern: str+) -> bool:+ for op, data in messages:+ if (+ op == "cell-op"+ and data["output"] is not None+ and re.match(pattern, data["output"]["data"])+ ):+ return True+ return False+++def test_capture_stdout(+ mocked_kernel: MockedKernel, exec_req: ExecReqProvider+) -> None:+ mocked_kernel.k.run(+ [+ exec_req.get(+ """+ import marimo as mo+ import sys+ with mo.capture_stdout() as buffer:+ sys.stdout.write('hello')+ sys.stderr.write('bye')+ """+ )+ ]+ )+ assert not mocked_kernel.stdout.messages+ assert mocked_kernel.stderr.messages == ["bye"]+ assert mocked_kernel.k.globals["buffer"].getvalue() == "hello"+++def test_capture_stderr(+ mocked_kernel: MockedKernel, exec_req: ExecReqProvider+) -> None:+ mocked_kernel.k.run(+ [+ exec_req.get(+ """+ import marimo as mo+ import sys+ with mo.capture_stderr() as buffer:+ sys.stdout.write('hello')+ sys.stderr.write('bye')+ """+ )+ ]+ )+ assert mocked_kernel.stdout.messages == ["hello"]+ assert not mocked_kernel.stderr.messages+ assert mocked_kernel.k.globals["buffer"].getvalue() == "bye"+++def test_capture_both(+ mocked_kernel: MockedKernel, exec_req: ExecReqProvider+) -> None:+ mocked_kernel.k.run(+ [+ # in python < 3.9, parenthesizing multiple context managers is+ # not allowed, hence the line continuation+ exec_req.get(+ """+ import marimo as mo+ import sys+ with mo.capture_stderr() as stderr, \+ mo.capture_stdout() as stdout:+ sys.stdout.write('hello')+ sys.stderr.write('bye')+ """+ )+ ]+ )+ assert not mocked_kernel.stdout.messages+ assert not mocked_kernel.stderr.messages+ assert mocked_kernel.k.globals["stdout"].getvalue() == "hello"+ assert mocked_kernel.k.globals["stderr"].getvalue() == "bye"+++def test_redirect_stdout(+ mocked_kernel: MockedKernel, exec_req: ExecReqProvider+) -> None:+ mocked_kernel.k.run(+ [+ exec_req.get(+ """+ import marimo as mo+ import sys+ with mo.redirect_stdout():+ sys.stdout.write('hello')+ sys.stderr.write('bye')+ """+ )+ ]+ )+ assert not mocked_kernel.stdout.messages+ assert mocked_kernel.stderr.messages == ["bye"]+ assert _has_output(mocked_kernel.stream.messages, r".*hello.*")+ assert not _has_output(mocked_kernel.stream.messages, r".*bye.*")+++def test_redirect_stderr(+ mocked_kernel: MockedKernel, exec_req: ExecReqProvider+) -> None:+ mocked_kernel.k.run(+ [+ exec_req.get(+ """+ import marimo as mo+ import sys+ with mo.redirect_stderr():+ sys.stdout.write('hello')+ sys.stderr.write('bye')+ """+ )+ ]+ )+ assert mocked_kernel.stdout.messages == ["hello"]+ assert not mocked_kernel.stderr.messages++ assert _has_output(mocked_kernel.stream.messages, r".*bye.*")+ assert not _has_output(mocked_kernel.stream.messages, r".*hello.*")+++def test_redirect_both(+ mocked_kernel: MockedKernel, exec_req: ExecReqProvider+) -> None:+ mocked_kernel.k.run(+ [+ exec_req.get(+ """+ import marimo as mo+ import sys+ with mo.redirect_stdout(), mo.redirect_stderr():+ sys.stdout.write('hello')+ sys.stderr.write('bye')+ """+ )+ ]+ )+ assert not mocked_kernel.stdout.messages+ assert not mocked_kernel.stderr.messages++ assert _has_output(mocked_kernel.stream.messages, r".*bye.*")+ assert _has_output(mocked_kernel.stream.messages, r".*hello.*")