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: printing in mo.Threads (#3628)

Akshay Agrawaldb1a68e13468
diff --git a/marimo/_messaging/print_override.py b/marimo/_messaging/print_override.py
new file mode 100644
index 0000000000..6a26e0d13e
--- /dev/null
+++ b/marimo/_messaging/print_override.py
@@ -0,0 +1,59 @@
+from __future__ import annotations
+
+import functools
+import threading
+from typing import Any
+
+from marimo._messaging.cell_output import CellChannel, CellOutput
+from marimo._messaging.ops import CellOp
+from marimo._runtime.context.types import (
+ ContextNotInitializedError,
+ get_context,
+)
+from marimo._runtime.threads import THREADS
+
+_original_print = print
+
+
+def print_override(*args: Any, **kwargs: Any) -> None:
+ """Override print to be aware of marimo threads.
+
+ When running marimo without mo.Threads, this just forwards to the built-in
+ print. When running with mo.Threads, it gets the threads cell ID and
+ forwards the print message to the appropriate cell.
+
+ This method is only necessary because the file descriptors for standard
+ out and standard in are currently redirected, and sys.stdout is not
+ always patched / is not aware of mo.Threads.
+ """
+ tid = threading.get_ident()
+ if tid not in THREADS:
+ _original_print(*args, **kwargs)
+ return
+
+ try:
+ ctx = get_context()
+ except ContextNotInitializedError:
+ _original_print(*args, **kwargs)
+ return
+
+ execution_context = ctx.execution_context
+ if execution_context is None:
+ _original_print(*args, **kwargs)
+ return
+
+ cell_id = execution_context.cell_id
+
+ sep = kwargs.get("sep", " ")
+ end = kwargs.get("end", "\n")
+ msg = sep.join([str(arg) for arg in args]) + end
+
+ CellOp(
+ cell_id=cell_id,
+ console=CellOutput(
+ channel=CellChannel.STDOUT,
+ mimetype="text/plain",
+ data=msg,
+ ),
+ ).broadcast(ctx.stream)
diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.py
index 68e8f70119..f9040cfab1 100644
--- a/marimo/_pyodide/pyodide_session.py
+++ b/marimo/_pyodide/pyodide_session.py
@@ -358,7 +358,9 @@ def _launch_pyodide_kernel(
stderr=stderr,
stdin=stdin,
module=patches.patch_main_module(
- file=app_metadata.filename, input_override=input_override
+ file=app_metadata.filename,
+ input_override=input_override,
+ print_override=None,
),
enqueue_control_request=_enqueue_control_request,
debugger_override=debugger,
diff --git a/marimo/_runtime/app/kernel_runner.py b/marimo/_runtime/app/kernel_runner.py
index d5c2735ab9..0e05d89d9d 100644
--- a/marimo/_runtime/app/kernel_runner.py
+++ b/marimo/_runtime/app/kernel_runner.py
@@ -71,7 +71,9 @@ class AppKernelRunner:
stdout=None,
stderr=None,
stdin=None,
- module=create_main_module(filename, None),
+ module=create_main_module(
+ filename, input_override=None, print_override=None
+ ),
user_config=DEFAULT_CONFIG,
enqueue_control_request=lambda _: None,
post_execution_hooks=[cache_output, _reset_matplotlib_context],
diff --git a/marimo/_runtime/app/script_runner.py b/marimo/_runtime/app/script_runner.py
index 76d8a15bd9..82b4a3003a 100644
--- a/marimo/_runtime/app/script_runner.py
+++ b/marimo/_runtime/app/script_runner.py
@@ -133,7 +133,9 @@ class AppScriptRunner:
post_execute_hooks: list[Callable[[], Any]],
) -> RunOutput:
with patch_main_module_context(
- create_main_module(file=self.filename, input_override=None)
+ create_main_module(
+ file=self.filename, input_override=None, print_override=None
+ )
) as module:
glbls = module.__dict__
outputs: dict[CellId_t, Any] = {}
@@ -150,7 +152,9 @@ class AppScriptRunner:
post_execute_hooks: list[Callable[[], Any]],
) -> RunOutput:
with patch_main_module_context(
- create_main_module(file=self.filename, input_override=None)
+ create_main_module(
+ file=self.filename, input_override=None, print_override=None
+ )
) as module:
glbls = module.__dict__
outputs: dict[CellId_t, Any] = {}
diff --git a/marimo/_runtime/context/script_context.py b/marimo/_runtime/context/script_context.py
index d846bbd22d..521936efea 100644
--- a/marimo/_runtime/context/script_context.py
+++ b/marimo/_runtime/context/script_context.py
@@ -49,7 +49,9 @@ class ScriptRuntimeContext(RuntimeContext):
@property
def globals(self) -> dict[str, Any]:
with patch_main_module_context(
- create_main_module(file=None, input_override=None)
+ create_main_module(
+ file=None, input_override=None, print_override=None
+ )
) as module:
glbls = module.__dict__
glbls.update(sys.modules["__main__"].__dict__)
diff --git a/marimo/_runtime/patches.py b/marimo/_runtime/patches.py
index 64bc08a561..e843d1ce70 100644
--- a/marimo/_runtime/patches.py
+++ b/marimo/_runtime/patches.py
@@ -117,7 +117,9 @@ del Loader; del MetaPathFinder
def create_main_module(
- file: str | None, input_override: Callable[[Any], str] | None
+ file: str | None,
+ input_override: Callable[[Any], str] | None,
+ print_override: Callable[[Any], None] | None,
) -> types.ModuleType:
# Every kernel gets its own main module, whose __dict__ attribute
# serves as the global namespace
@@ -129,6 +131,8 @@ def create_main_module(
if input_override is not None:
_module.__dict__.setdefault("input", input_override)
+ if print_override is not None:
+ _module.__dict__.setdefault("print", print_override)
if file is not None:
_module.__dict__.setdefault("__file__", file)
@@ -145,14 +149,16 @@ def create_main_module(
def patch_main_module(
- file: str | None, input_override: Callable[[Any], str] | None
+ file: str | None,
+ input_override: Callable[[Any], str] | None,
+ print_override: Callable[[Any], None] | None,
) -> types.ModuleType:
"""Patches __main__ module
- Makes functions pickleable
- Loads some overrides and mocks into globals
"""
- _module = create_main_module(file, input_override)
+ _module = create_main_module(file, input_override, print_override)
# TODO(akshayka): In run mode, this can introduce races between different
# kernel threads, since they each share sys.modules. Unfortunately, Python
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 255dc6d301..4c38fcc77c 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -54,6 +54,7 @@ from marimo._messaging.ops import (
VariableValue,
VariableValues,
)
+from marimo._messaging.print_override import print_override
from marimo._messaging.streams import (
QueuePipe,
ThreadSafeStderr,
@@ -2198,7 +2199,9 @@ def launch_kernel(
stderr=stderr,
stdin=stdin,
module=patches.patch_main_module(
- file=app_metadata.filename, input_override=input_override
+ file=app_metadata.filename,
+ input_override=input_override,
+ print_override=print_override,
),
debugger_override=debugger,
user_config=user_config,
diff --git a/marimo/_runtime/threads.py b/marimo/_runtime/threads.py
index c8492f92ac..4481802f82 100644
--- a/marimo/_runtime/threads.py
+++ b/marimo/_runtime/threads.py
@@ -16,6 +16,9 @@ from marimo._runtime.context.types import (
runtime_context_installed,
)
+# Set of thread ids for running mo.Threads
+THREADS = set()
+
class Thread(threading.Thread):
"""A Thread subclass that is aware of marimo internals.
@@ -24,9 +27,12 @@ class Thread(threading.Thread):
but `mo.Thread`s are able to communicate with the marimo
frontend, whereas `threading.Thread` can't.
- Currently, threads can append to a cell's output using
- `mo.output.append`, but messages written to stdout and stderr won't
- be forwarded to the frontend.
+ Threads can append to a cell's output using `mo.output.append`, or to the
+ console output area using `print`. The corresponding outputs will be
+ forwarded to the frontend.
+
+ Writing directly to sys.stdout or sys.stderr, or to file descriptors 1 and
+ 2, is not yet supported.
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
@@ -84,4 +90,7 @@ class Thread(threading.Thread):
cell_id=self._marimo_ctx.stream.cell_id, # type: ignore
setting_element_value=False,
)
+ thread_id = threading.get_ident()
+ THREADS.add(thread_id)
super().run()
+ THREADS.remove(thread_id)
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index c8db51979b..3b8c4e136e 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -1090,7 +1090,7 @@ class TestExecution:
query_params={}, filename=filename, cli_args={}
),
enqueue_control_request=lambda _: None,
- module=create_main_module(None, None),
+ module=create_main_module(None, None, None),
)
initialize_kernel_context(
kernel=k,
@@ -1151,7 +1151,7 @@ class TestExecution:
query_params={}, filename=filename, cli_args={}
),
enqueue_control_request=lambda _: None,
- module=create_main_module(None, None),
+ module=create_main_module(None, None, None),
)
assert str(tmp_path) in sys.path
assert str(tmp_path) == sys.path[0]
diff --git a/tests/_runtime/test_threads.py b/tests/_runtime/test_threads.py
index 8bc35afad2..4bea4dc5ec 100644
--- a/tests/_runtime/test_threads.py
+++ b/tests/_runtime/test_threads.py
@@ -32,7 +32,7 @@ async def test_thread_set_global(k: Kernel, exec_req: ExecReqProvider) -> None:
async def test_thread_has_own_stream(
k: Kernel, exec_req: ExecReqProvider
) -> None:
- """Test that a thread starts and runs."""
+ """Test that a thread starts, runs, has its own stream."""
await k.run(
[
@@ -63,7 +63,7 @@ async def test_thread_has_own_stream(
async def test_thread_output_append(
k: Kernel, exec_req: ExecReqProvider
) -> None:
- """Test that a thread starts and runs."""
+ """Test that a thread starts, runs, and appends to output."""
await k.run(
[
@@ -97,3 +97,41 @@ async def test_thread_output_append(
assert len(thread_stream.messages) == 2
assert "hello" in thread_stream.messages[0][1]["output"]["data"]
assert "world" in thread_stream.messages[1][1]["output"]["data"]
+
+
+async def test_thread_print(k: Kernel, exec_req: ExecReqProvider) -> None:
+ """Test that a thread starts, runs, and prints."""
+
+ await k.run(
+ [
+ exec_req.get("import marimo as mo"),
+ exec_req.get(
+ """
+ stream = mo._runtime.context.get_context().stream
+ thread_stream = None
+ def target():
+ global thread_stream
+ import marimo as mo
+ print("hello")
+ print("world")
+ thread_stream = mo._runtime.context.get_context().stream
+ t = mo.Thread(target=target); t.start(); t.join()
+ """
+ ),
+ ]
+ )
+
+ # thread run should be basically instantaneous, but sleep just in case ...
+ assert not k.errors
+ time.sleep(0.01) # noqa: ASYNC251
+ # The main thread should not have any output, but the new thread should
+ stream = k.globals["stream"]
+ for m in stream.messages:
+ assert ("console" not in m[1]) or not m[1]["console"]
+
+ thread_stream = k.globals["thread_stream"]
+ assert len(thread_stream.messages) == 2
+ assert "hello" in thread_stream.messages[0][1]["console"]["data"]
+ assert thread_stream.messages[0][1]["console"]["channel"] == "stdout"
+ assert "world" in thread_stream.messages[1][1]["console"]["data"]
+ assert thread_stream.messages[1][1]["console"]["channel"] == "stdout"
diff --git a/tests/conftest.py b/tests/conftest.py
index 84cf966af0..f4f7fbc1a4 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -18,6 +18,7 @@ from marimo._ast.cell import CellId_t
from marimo._config.config import DEFAULT_CONFIG
from marimo._messaging.mimetypes import KnownMimeType
from marimo._messaging.ops import CellOp, MessageOperation
+from marimo._messaging.print_override import print_override
from marimo._messaging.streams import (
ThreadSafeStderr,
ThreadSafeStdin,
@@ -132,7 +133,9 @@ class MockedKernel:
self.stdin = MockStdin(self.stream)
self._main = sys.modules["__main__"]
module = patches.patch_main_module(
- file=None, input_override=input_override
+ file=None,
+ input_override=input_override,
+ print_override=print_override,
)
self.k = Kernel(