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: support input() and stdin (#587)
Akshay Agrawal901d40ddbf08
diff --git a/codecov.yml b/codecov.ymlindex 38f4fbc765..0a010023b0 100644--- a/codecov.yml+++ b/codecov.yml@@ -8,3 +8,9 @@ coverage:# this allows a 5% drop from the previous base commit coverage# we'll decrease this as our testing maturesthreshold: 5%+ patch:+ default:+ target: auto+ # this allows a 15% drop from the previous base commit coverage+ # we'll decrease this as our testing matures+ threshold: 15%diff --git a/frontend/e2e-tests/py/stdin.py b/frontend/e2e-tests/py/stdin.pynew file mode 100644index 0000000000..64d2067beb--- /dev/null+++ b/frontend/e2e-tests/py/stdin.py@@ -0,0 +1,28 @@+# Copyright 2024 Marimo. All rights reserved.+import marimo++__generated_with = "0.1.77"+app = marimo.App()+++def __():+ import marimo as mo++ return (mo,)+++def __():+ value = input("what is your name?")+ return (value,)+++def __(mo, value):+ mo.md(f"## 👋 Hi {value}")+ return+++if __name__ == "__main__":+ app.run()diff --git a/frontend/e2e-tests/stdin.spec.ts b/frontend/e2e-tests/stdin.spec.tsnew file mode 100644index 0000000000..cc8713e454--- /dev/null+++ b/frontend/e2e-tests/stdin.spec.ts@@ -0,0 +1,34 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { test, expect } from "@playwright/test";+import { getAppUrl } from "../playwright.config";++const appUrl = getAppUrl("stdin.py//edit");++test("stdin works", async ({ page }) => {+ await page.goto(appUrl);++ expect(page.getByText("stdin.py")).toBeTruthy();++ // Check that "what is your name?" exists in the console+ await expect(page.getByTestId("console-output-area")).toHaveText(+ "what is your name?"+ );++ // Expect loading spinner+ await expect(page.getByTestId("loading-indicator")).toBeVisible();++ // Get input inside the console+ const consoleInput = page+ .getByTestId("console-output-area")+ .getByRole("textbox");+ // Type "marimo" into the console+ await consoleInput.fill("marimo");+ // Hit enter+ await consoleInput.press("Enter");++ // Check that "Hi, marimo" exists on the page+ await expect(page.getByText("Hi marimo")).toBeVisible();++ // Expect not loading spinner+ await expect(page.getByTestId("loading-indicator")).not.toBeVisible();+});diff --git a/frontend/playwright.config.ts b/frontend/playwright.config.tsindex bd87990131..d429f1aa38 100644--- a/frontend/playwright.config.ts+++ b/frontend/playwright.config.ts@@ -36,6 +36,7 @@ const appToOptions = {"layout_grid_max_width.py//run": { port: port(), command: "run" },"output.py//run": { port: port(), command: "run" },"kitchen_sink.py//edit": { port: port(), command: "edit" },+ "stdin.py//edit": { port: port(), command: "edit" },} satisfies Record<string, ServerOptions>;export type ApplicationNames = keyof typeof appToOptions;diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsxindex fd7da4a3c3..9397423ca6 100644--- a/frontend/src/components/editor/Cell.tsx+++ b/frontend/src/components/editor/Cell.tsx@@ -11,7 +11,7 @@ import {useRef,} from "react";-import { saveCellConfig, sendRun } from "@/core/network/requests";+import { saveCellConfig, sendRun, sendStdin } from "@/core/network/requests";import { autocompletionKeymap } from "@/core/codemirror/cm";import { clearTooltips } from "@/core/codemirror/completion/hints";import { UserConfig } from "../../core/config/config-schema";@@ -81,6 +81,7 @@ export interface CellProps| "moveCell"| "moveToNextCell"| "updateCellConfig"+ | "setStdinResponse"| "sendToBottom"| "sendToTop"> {@@ -125,6 +126,7 @@ const CellComponent = (deleteCell,focusCell,moveCell,+ setStdinResponse,moveToNextCell,updateCellConfig,sendToBottom,@@ -442,6 +444,10 @@ const CellComponent = (consoleOutputs={consoleOutputs}stale={consoleOutputStale}cellName={name}+ onSubmitDebugger={(text, index) => {+ setStdinResponse({ cellId, response: text, outputIndex: index });+ sendStdin({ text });+ }}cellId={cellId}/></SortableCell>diff --git a/frontend/src/components/editor/output/ConsoleOutput.tsx b/frontend/src/components/editor/output/ConsoleOutput.tsxindex 416af8f310..3a9cade9a2 100644--- a/frontend/src/components/editor/output/ConsoleOutput.tsx+++ b/frontend/src/components/editor/output/ConsoleOutput.tsx@@ -6,16 +6,18 @@ import { cn } from "@/utils/cn";import { DEFAULT_CELL_NAME } from "@/core/cells/names";import { NameCellContentEditable } from "../actions/name-cell-input";import { CellId } from "@/core/cells/ids";+import { Input } from "@/components/ui/input";interface Props {cellId: CellId;cellName: string;consoleOutputs: OutputMessage[];stale: boolean;+ onSubmitDebugger: (text: string, index: number) => void;}export const ConsoleOutput = (props: Props): React.ReactNode => {- const { consoleOutputs, stale, cellName, cellId } = props;+ const { consoleOutputs, stale, cellName, cellId, onSubmitDebugger } = props;const hasOutputs = consoleOutputs.length > 0;if (!hasOutputs && cellName === DEFAULT_CELL_NAME) {@@ -25,17 +27,48 @@ export const ConsoleOutput = (props: Props): React.ReactNode => {return (<divtitle={stale ? "This console output is stale" : undefined}+ data-testid="console-output-area"className={cn("console-output-area overflow-hidden rounded-b-lg",stale && "marimo-output-stale",hasOutputs ? "p-5" : "p-3")}>- {consoleOutputs.map((output, idx) => (- <React.Fragment key={idx}>- {formatOutput({ message: output })}- </React.Fragment>- ))}+ {consoleOutputs.map((output, idx) => {+ if (output.channel === "stdin") {+ if (output.response == null) {+ return (+ <div key={idx} className="flex gap-2 items-center">+ <span>{output.data}</span>+ <Input+ type="text"+ autoComplete="off"+ autoFocus={true}+ className="m-0"+ placeholder="stdin"+ onKeyDown={(e) => {+ if (e.key === "Enter" && !e.shiftKey) {+ onSubmitDebugger(e.currentTarget.value, idx);+ }+ }}+ />+ </div>+ );+ }+ return (+ <div key={idx} className="flex gap-2 items-center">+ <span>{output.data}</span>+ <span className="text-[var(--sky-11)]">{output.response}</span>+ </div>+ );+ }++ return (+ <React.Fragment key={idx}>+ {formatOutput({ message: output })}+ </React.Fragment>+ );+ })}<NameCellContentEditablevalue={cellName}cellId={cellId}diff --git a/frontend/src/components/editor/output/TextOutput.tsx b/frontend/src/components/editor/output/TextOutput.tsxindex 3b2dc2fb46..19622def24 100644--- a/frontend/src/components/editor/output/TextOutput.tsx+++ b/frontend/src/components/editor/output/TextOutput.tsx@@ -5,7 +5,7 @@ import { cn } from "@/utils/cn";interface Props {text: string;- channel?: OutputChannel;+ channel?: OutputChannel | "stdin";}export const TextOutput = ({ text, channel }: Props): JSX.Element => {diff --git a/frontend/src/components/editor/renderers/CellArray.tsx b/frontend/src/components/editor/renderers/CellArray.tsxindex e40a5aaeae..1c9cabe65b 100644--- a/frontend/src/components/editor/renderers/CellArray.tsx+++ b/frontend/src/components/editor/renderers/CellArray.tsx@@ -53,6 +53,7 @@ export const CellArray: React.FC<CellArrayProps> = ({unfoldAll,sendToBottom,sendToTop,+ setStdinResponse,} = useCellActions();const { theme } = useTheme();const { togglePanel } = useChromeActions();@@ -114,6 +115,7 @@ export const CellArray: React.FC<CellArrayProps> = ({deleteCell={onDeleteCell}focusCell={focusCell}moveToNextCell={moveToNextCell}+ setStdinResponse={setStdinResponse}updateCellConfig={updateCellConfig}moveCell={moveCell}mode={mode}diff --git a/frontend/src/core/App.tsx b/frontend/src/core/App.tsxindex bfaffa33dc..21d1107036 100644--- a/frontend/src/core/App.tsx+++ b/frontend/src/core/App.tsx@@ -391,6 +391,7 @@ const DisconnectedIcon = () => (const RunningIcon = () => (<divclassName={topLeftStatus}+ data-testid="loading-indicator"title={"Marimo is busy computing. Hang tight!"}><HourglassIcon className="running-app-icon" size={30} strokeWidth={1} />diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.tsindex eb3b41b0b3..e4b7e61a05 100644--- a/frontend/src/core/cells/cells.ts+++ b/frontend/src/core/cells/cells.ts@@ -393,6 +393,33 @@ const { reducer, createActions } = createReducer(initialNotebookState, {cellLogs: [...nextState.cellLogs, ...getCellLogsForMessage(message)],};},+ setStdinResponse: (+ state,+ action: { cellId: CellId; response: string; outputIndex: number }+ ) => {+ const { cellId, response, outputIndex } = action;+ return updateCellRuntimeState(state, cellId, (cell) => {+ const consoleOutputs = [...cell.consoleOutputs];+ const stdinOutput = consoleOutputs[outputIndex];+ if (stdinOutput.channel !== "stdin") {+ Logger.warn("Expected stdin output");+ return cell;+ }++ consoleOutputs[outputIndex] = {+ channel: "stdin",+ mimetype: stdinOutput.mimetype,+ data: stdinOutput.data,+ timestamp: stdinOutput.timestamp,+ response,+ };++ return {+ ...cell,+ consoleOutputs,+ };+ });+ },setCells: (state, cells: CellData[]) => {return {...state,diff --git a/frontend/src/core/kernel/messages.ts b/frontend/src/core/kernel/messages.tsindex 61e300b899..0c1bfc0c07 100644--- a/frontend/src/core/kernel/messages.ts+++ b/frontend/src/core/kernel/messages.ts@@ -58,6 +58,17 @@ export type OutputMessage =mimetype: "application/json";data: unknown;timestamp: number;+ }+ | {+ channel: "stdin";+ mimetype: "text/plain";+ data: string;+ /**+ * This is not saved to the server, but we update this field+ * after sending the message to the kernel.+ */+ response?: string;+ timestamp: number;};/**diff --git a/frontend/src/core/network/requests.ts b/frontend/src/core/network/requests.tsindex a3ecab8a1a..e0182d33a4 100644--- a/frontend/src/core/network/requests.ts+++ b/frontend/src/core/network/requests.ts@@ -21,6 +21,7 @@ import {SendFunctionRequest,RunRequests,EditRequests,+ SendStdin,} from "./types";import { invariant } from "@/utils/invariant";@@ -130,6 +131,9 @@ function createNetworkRequests(): EditRequests & RunRequests {sendFunctionRequest: (request) => {return API.post<SendFunctionRequest>("/kernel/function_call/", request);},+ sendStdin: (request) => {+ return API.post<SendStdin>("/kernel/stdin/", request);+ },readCode: () => {return API.post<{}, { contents: string }>("/kernel/read_code/", {});},@@ -140,6 +144,7 @@ export const {sendComponentValues,sendRename,sendSave,+ sendStdin,sendFormat,sendInterrupt,sendShutdown,diff --git a/frontend/src/core/network/static-requests.ts b/frontend/src/core/network/static-requests.tsindex 625f253fbf..53c36e2b56 100644--- a/frontend/src/core/network/static-requests.ts+++ b/frontend/src/core/network/static-requests.ts@@ -48,6 +48,7 @@ export function createStaticRequests(): EditRequests & RunRequests {saveUserConfig: throwNotInEditMode,saveAppConfig: throwNotInEditMode,saveCellConfig: throwNotInEditMode,+ sendStdin: throwNotInEditMode,readCode: throwNotInEditMode,};}diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.tsindex e65e831ad4..1bba922c31 100644--- a/frontend/src/core/network/types.ts+++ b/frontend/src/core/network/types.ts@@ -97,6 +97,10 @@ export interface SendFunctionRequest {functionName: string;}+export interface SendStdin {+ text: string;+}+interface ValueUpdate {objectId: string;value: unknown;@@ -117,6 +121,7 @@ export interface RunRequests {export interface EditRequests {sendRename: (filename: string | null) => Promise<null>;sendSave: (request: SaveKernelRequest) => Promise<null>;+ sendStdin: (request: SendStdin) => Promise<null>;sendRun: (cellIds: CellId[], codes: string[]) => Promise<null>;sendInterrupt: () => Promise<null>;sendShutdown: () => Promise<null>;diff --git a/frontend/src/stories/cell.stories.tsx b/frontend/src/stories/cell.stories.tsxindex e63cbe40a1..d8df928f69 100644--- a/frontend/src/stories/cell.stories.tsx+++ b/frontend/src/stories/cell.stories.tsx@@ -44,6 +44,7 @@ const props: CellProps = {sendToBottom: Logger.log,sendToTop: Logger.log,updateCellConfig: Logger.log,+ setStdinResponse: Logger.log,config: {},userConfig: {completion: {diff --git a/marimo/_messaging/console_output_worker.py b/marimo/_messaging/console_output_worker.pyindex 722b922784..a2f256ca74 100644--- a/marimo/_messaging/console_output_worker.py+++ b/marimo/_messaging/console_output_worker.py@@ -15,7 +15,7 @@ if TYPE_CHECKING:from marimo._messaging.streams import Stream-StreamT = Literal["stdout", "stderr"]+StreamT = Literal["stdout", "stderr", "stdin"]# Flush console outputs every 10msTIMEOUT_S = 0.01diff --git a/marimo/_messaging/streams.py b/marimo/_messaging/streams.pyindex 14324e3a18..204c6c5753 100644--- a/marimo/_messaging/streams.py+++ b/marimo/_messaging/streams.py@@ -1,12 +1,15 @@# Copyright 2023 Marimo. All rights reserved.from __future__ import annotations+import io+import multiprocessing as mpimport os+import queueimport sysimport threadingfrom collections import dequefrom multiprocessing.connection import Connection-from typing import Any, Optional+from typing import Any, Iterable, Optionalfrom marimo import _loggersfrom marimo._ast.cell import CellId_t@@ -43,12 +46,18 @@ STD_STREAM_MAX_BYTES = int(os.getenv("MARIMO_STD_STREAM_MAX_BYTES", 1_000_000))class Stream:"""A thread-safe wrapper around a pipe."""- def __init__(self, pipe: Connection, cell_id: Optional[CellId_t] = None):+ def __init__(+ self,+ pipe: Connection,+ input_queue: mp.Queue[str] | queue.Queue[str],+ cell_id: Optional[CellId_t] = None,+ ):self.pipe = pipeself.cell_id = cell_id# A single stream is shared by the kernel and the code completion# worker. The lock should almost always be uncontended.self.stream_lock = threading.Lock()+# Console outputs are bufferedself.console_msg_cv = threading.Condition(threading.Lock())self.console_msg_queue: deque[ConsoleMsg] = deque()@@ -58,6 +67,9 @@ class Stream:)self.buffered_console_thread.start()+ # stdin messages are pulled from this queue+ self.input_queue = input_queue+def write(self, op: str, data: dict[Any, Any]) -> None:with self.stream_lock:try:@@ -68,11 +80,26 @@ class Stream:LOGGER.debug("Error when writing (op: %s) to pipe: %s", op, e)-class Stdout:+class Stdout(io.TextIOBase):+ name = "stdout"+def __init__(self, stream: Stream):self.stream = stream- def write(self, data: str) -> None:+ def writable(self) -> bool:+ return True++ def readable(self) -> bool:+ return False++ def seekable(self) -> bool:+ return False++ def flush(self) -> None:+ # TODO(akshayka): maybe force the buffered writer to write+ return++ def write(self, data: str) -> int:assert self.stream.cell_id is not Noneif not isinstance(data, str):raise TypeError(@@ -88,10 +115,19 @@ class Stdout:)with self.stream.console_msg_cv:self.stream.console_msg_cv.notify()+ return len(data)- def flush(self) -> None:- # TODO(akshayka): maybe force the buffered writer to write- return+ # Buffer type not available python < 3.12, hence type ignore+ def writelines(self, sequence: Iterable[str]) -> None: # type: ignore[override] # noqa: E501+ for line in sequence:+ self.write(line)+++class Stderr(io.TextIOBase):+ name = "stderr"++ def __init__(self, stream: Stream):+ self.stream = streamdef writable(self) -> bool:return True@@ -102,12 +138,11 @@ class Stdout:def seekable(self) -> bool:return False+ def flush(self) -> None:+ # TODO(akshayka): maybe force the buffered writer to write+ return-class Stderr:- def __init__(self, stream: Stream):- self.stream = stream-- def write(self, data: str) -> None:+ def write(self, data: str) -> int:assert self.stream.cell_id is not Noneif not isinstance(data, str):raise TypeError(@@ -127,15 +162,62 @@ class Stderr:))self.stream.console_msg_cv.notify()+ return len(data)++ def writelines(self, sequence: Iterable[str]) -> None: # type: ignore[override] # noqa: E501+ for line in sequence:+ self.write(line)- def flush(self) -> None:- return++class Stdin(io.TextIOBase):+ """Implements a subset of stdin."""++ name = "stdin"++ def __init__(self, stream: Stream):+ self.stream = streamdef writable(self) -> bool:- return True+ return Falsedef readable(self) -> bool:- return False+ return True- def seekable(self) -> bool:- return False+ def _readline_with_prompt(self, prompt: str = "") -> str:+ """Read input from the standard in stream, with an optional prompt."""+ assert self.stream.cell_id is not None+ if not isinstance(prompt, str):+ raise TypeError(+ "prompt must be a str, not %s" % type(prompt).__name__+ )+ if sys.getsizeof(prompt) > STD_STREAM_MAX_BYTES:+ prompt = (+ "Warning: marimo truncated a very large console output.\n"+ + prompt[: int(STD_STREAM_MAX_BYTES)]+ + " ... "+ )++ with self.stream.console_msg_cv:+ # This sends a prompt request to the frontend.+ self.stream.console_msg_queue.append(+ ConsoleMsg(+ stream="stdin", cell_id=self.stream.cell_id, data=prompt+ )+ )+ self.stream.console_msg_cv.notify()++ return self.stream.input_queue.get()++ def readline(self, size: int | None = -1) -> str: # type: ignore[override] # noqa: E501+ # size only included for compatibility with sys.stdin.readline API;+ # we don't support it.+ del size+ return self._readline_with_prompt(prompt="")++ def readlines(self, hint: int | None = -1) -> list[str]: # type: ignore[override] # noqa: E501+ # Just an alias for readline.+ #+ # hint only included for compatibility with sys.stdin.readlines API;+ # we don't support it.+ del hint+ return self._readline_with_prompt(prompt="").split("\n")diff --git a/marimo/_runtime/context.py b/marimo/_runtime/context.pyindex f8ad7832ef..68ef7cf8fb 100644--- a/marimo/_runtime/context.py+++ b/marimo/_runtime/context.py@@ -18,7 +18,7 @@ from marimo._runtime.functions import FunctionRegistryif TYPE_CHECKING:from marimo._ast.cell import CellId_t- from marimo._messaging.streams import Stderr, Stdout, Stream+ from marimo._messaging.streams import Stderr, Stdin, Stdout, Streamfrom marimo._plugins.ui._core.registry import UIElementRegistryfrom marimo._runtime.runtime import Kernelfrom marimo._runtime.virtual_file import VirtualFileRegistry@@ -57,6 +57,7 @@ class RuntimeContext:stream: Streamstdout: Optional[Stdout]stderr: Optional[Stderr]+ stdin: Optional[Stdin]_id_provider: Optional[IDProvider] = None@property@@ -105,10 +106,14 @@ def initialize_context(stream: Stream,stdout: Optional[Stdout],stderr: Optional[Stderr],+ stdin: Optional[Stdin],) -> None:"""Initializes thread-local/session-specific context.Must be called exactly once for each client thread.++ stdout, stderr, and stdin are optional because in `run` mode the+ standard streams are not redirected/replaced."""from marimo._plugins.ui._core.registry import UIElementRegistryfrom marimo._runtime.virtual_file import VirtualFileRegistry@@ -127,6 +132,7 @@ def initialize_context(stream=stream,stdout=stdout,stderr=stderr,+ stdin=stdin,)_THREAD_LOCAL_CONTEXT.initialize(runtime_context=runtime_context)diff --git a/marimo/_runtime/input_override.py b/marimo/_runtime/input_override.pynew file mode 100644index 0000000000..b1db950e97--- /dev/null+++ b/marimo/_runtime/input_override.py@@ -0,0 +1,10 @@+# Copyright 2024 Marimo. All rights reserved.+import functools++from marimo._runtime.context import get_context++[email protected](input)+def input_override(prompt: str = "") -> str:+ assert (stdin := get_context().stdin) is not None+ return stdin._readline_with_prompt(prompt)diff --git a/marimo/_runtime/redirect_streams.py b/marimo/_runtime/redirect_streams.pyindex 1476da982a..ad83babb65 100644--- a/marimo/_runtime/redirect_streams.py+++ b/marimo/_runtime/redirect_streams.py@@ -54,6 +54,8 @@ def redirect_streams(cell_id: CellId_t) -> Iterator[None]:ctx.stream.cell_id = Nonereturn+ # Redirect file descriptors for writable streams (stdout, stderr).+ ## All six of these file descriptors will need to be closed laterstdout_duped, stdout_read_fd, stdout_fd = dup2newfd(sys.stdout.fileno())stderr_duped, stderr_read_fd, stderr_fd = dup2newfd(sys.stderr.fileno())@@ -72,10 +74,14 @@ def redirect_streams(cell_id: CellId_t) -> Iterator[None]:target=forward_os_stream, args=(ctx.stderr, stderr_read_fd))+ # NB: Python doesn't allow monkey patching methods builtins, so+ # we replace these streams outrightpy_stdout = sys.stdoutpy_stderr = sys.stderr+ py_stdin = sys.stdinsys.stdout = ctx.stdout # type: ignoresys.stderr = ctx.stderr # type: ignore+ sys.stdin = ctx.stdin # type: ignorestdout_thread.start()stderr_thread.start()@@ -103,8 +109,9 @@ def redirect_streams(cell_id: CellId_t) -> Iterator[None]:os.close(stdout_read_fd)os.close(stderr_read_fd)- # Restore Python stdout/stderr+ # Restore Python stdout/stderr/stdinsys.stdout = py_stdoutsys.stderr = py_stderr+ sys.stdin = py_stdinctx.stream.cell_id = Nonediff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex d9f5f72e69..7e500bbffe 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -15,7 +15,7 @@ import threadingimport timeimport tracebackfrom collections.abc import Iterable, Sequence-from typing import Any, Iterator, Optional+from typing import Any, Callable, Iterator, Optionalfrom marimo import _loggersfrom marimo._ast.cell import CellConfig, CellId_t, parse_cell@@ -40,7 +40,7 @@ from marimo._messaging.ops import (VariableValue,VariableValues,)-from marimo._messaging.streams import Stderr, Stdout, Stream+from marimo._messaging.streams import Stderr, Stdin, Stdout, Streamfrom marimo._output import formattingfrom marimo._output.rich_help import mddocfrom marimo._plugins.core.web_component import JSONType@@ -54,6 +54,7 @@ from marimo._runtime.context import (initialize_context,)from marimo._runtime.control_flow import MarimoInterrupt, MarimoStopError+from marimo._runtime.input_override import input_overridefrom marimo._runtime.redirect_streams import redirect_streamsfrom marimo._runtime.requests import (CompletionRequest,@@ -152,13 +153,23 @@ class CellMetadata:class Kernel:+ """Kernel that manages the dependency graph and its execution.++ Args:++ - cell_configs: initial configuration for each cell+ - input_override: a function that overrides the builtin input() function+ """+def __init__(self,cell_configs: dict[CellId_t, CellConfig],+ input_override: Callable[[Any], str] = input_override,) -> None:self.globals: dict[Any, Any] = {"__name__": "__main__","__builtins__": globals()["__builtins__"],+ "input": input_override,}self.graph = dataflow.DirectedGraph()self.cell_metadata: dict[CellId_t, CellMetadata] = {@@ -985,7 +996,8 @@ class Kernel:def launch_kernel(- execution_queue: mp.Queue[Request] | queue.Queue[Request],+ control_queue: mp.Queue[Request] | queue.Queue[Request],+ input_queue: mp.Queue[str] | queue.Queue[str],socket_addr: tuple[str, int],is_edit_mode: bool,configs: dict[CellId_t, CellConfig],@@ -1006,18 +1018,22 @@ def launch_kernel(return# Create communication channels- stream = Stream(pipe)+ stream = Stream(pipe=pipe, input_queue=input_queue)# Console output is hidden in run mode, so no need to redirect# (redirection of console outputs is not thread-safe anyway)stdout = Stdout(stream) if is_edit_mode else Nonestderr = Stderr(stream) if is_edit_mode else None+ # TODO(akshayka): stdin in run mode? input(prompt) uses stdout, which+ # isn't currently available in run mode.+ stdin = Stdin(stream) if is_edit_mode else None- kernel = Kernel(cell_configs=configs)+ kernel = Kernel(cell_configs=configs, input_override=input_override)initialize_context(kernel=kernel,stream=stream,stdout=stdout,stderr=stderr,+ stdin=stdin,)if is_edit_mode:@@ -1092,7 +1108,7 @@ def launch_kernel(while True:try:- request = execution_queue.get()+ request = control_queue.get()except Exception as e:# triggered on Windows when quit with Ctrl+CLOGGER.debug("kernel queue.get() failed %s", e)diff --git a/marimo/_server/api/__init__.py b/marimo/_server/api/__init__.pyindex d9f3daac71..c693d5dd2e 100644--- a/marimo/_server/api/__init__.py+++ b/marimo/_server/api/__init__.py@@ -15,6 +15,7 @@ __all__ = ["SaveUserConfigurationHandler","SetCellConfigHandler","SetUIElementValueHandler",+ "StdinHandler","VirtualFileHandler",]@@ -35,4 +36,5 @@ from marimo._server.api.save_app_config import SaveAppConfigurationHandlerfrom marimo._server.api.save_user_config import SaveUserConfigurationHandlerfrom marimo._server.api.set_cell_config import SetCellConfigHandlerfrom marimo._server.api.set_ui_element_value import SetUIElementValueHandler+from marimo._server.api.stdin import StdinHandlerfrom marimo._server.api.virtual_file import VirtualFileHandlerdiff --git a/marimo/_server/api/code_complete.py b/marimo/_server/api/code_complete.pyindex 3adf0ca3a9..f5dd37a3ae 100644--- a/marimo/_server/api/code_complete.py+++ b/marimo/_server/api/code_complete.py@@ -24,7 +24,7 @@ class CodeCompleteHandler(ValidatedHandler):def post(self) -> None:args = parse_raw(self.request.body, CodeComplete)session = sessions.require_session_from_header(self.request.headers)- session.queue.put(+ session.control_queue.put(requests.CompletionRequest(completion_id=args.id,document=args.document,diff --git a/marimo/_server/api/delete.py b/marimo/_server/api/delete.pyindex 0a7281f95c..3e8f1752ca 100644--- a/marimo/_server/api/delete.py+++ b/marimo/_server/api/delete.py@@ -24,4 +24,4 @@ class DeleteHandler(ValidatedHandler):args = parse_raw(self.request.body, Delete)cell_id = CellId_t(args.cell_id)request = requests.DeleteRequest(cell_id=cell_id)- session.queue.put(request)+ session.control_queue.put(request)diff --git a/marimo/_server/api/function_call.py b/marimo/_server/api/function_call.pyindex 1f9e1db074..608f8fd123 100644--- a/marimo/_server/api/function_call.py+++ b/marimo/_server/api/function_call.py@@ -34,4 +34,4 @@ class FunctionHandler(ValidatedHandler):function_name=args.function_name,args=args.args,)- session.queue.put(request)+ session.control_queue.put(request)diff --git a/marimo/_server/api/instantiate.py b/marimo/_server/api/instantiate.pyindex ee7ad6f61b..23c9f85524 100644--- a/marimo/_server/api/instantiate.py+++ b/marimo/_server/api/instantiate.py@@ -50,4 +50,4 @@ class InstantiateHandler(ValidatedHandler):zip(args.object_ids, args.values)),)- session.queue.put(request)+ session.control_queue.put(request)diff --git a/marimo/_server/api/run.py b/marimo/_server/api/run.pyindex 90242ed921..4c2c09fa19 100644--- a/marimo/_server/api/run.py+++ b/marimo/_server/api/run.py@@ -38,4 +38,4 @@ class RunHandler(ValidatedHandler):for cid, code in zip(args.cell_ids, args.codes)))- session.queue.put(request)+ session.control_queue.put(request)diff --git a/marimo/_server/api/save_user_config.py b/marimo/_server/api/save_user_config.pyindex 7128626db4..1ff0b9e21a 100644--- a/marimo/_server/api/save_user_config.py+++ b/marimo/_server/api/save_user_config.py@@ -75,4 +75,6 @@ class SaveUserConfigurationHandler(ValidatedHandler):LOGGER.debug("Starting copilot server")sessions.get_manager().start_lsp_server()# Update the kernel's view of the config- session.queue.put(requests.ConfigurationRequest(str(args.config)))+ session.control_queue.put(+ requests.ConfigurationRequest(str(args.config))+ )diff --git a/marimo/_server/api/set_cell_config.py b/marimo/_server/api/set_cell_config.pyindex 72c9c0ad80..aa86e73a25 100644--- a/marimo/_server/api/set_cell_config.py+++ b/marimo/_server/api/set_cell_config.py@@ -21,4 +21,4 @@ class SetCellConfigHandler(ValidatedHandler):def post(self) -> None:session = sessions.require_session_from_header(self.request.headers)args = parse_raw(self.request.body, SetCellConfig)- session.queue.put(requests.SetCellConfigRequest(args.configs))+ session.control_queue.put(requests.SetCellConfigRequest(args.configs))diff --git a/marimo/_server/api/set_ui_element_value.py b/marimo/_server/api/set_ui_element_value.pyindex ef2aaf5f66..af079e3e40 100644--- a/marimo/_server/api/set_ui_element_value.py+++ b/marimo/_server/api/set_ui_element_value.py@@ -22,7 +22,7 @@ class SetUIElementValueHandler(ValidatedHandler):def post(self) -> None:session = sessions.require_session_from_header(self.request.headers)args = parse_raw(self.request.body, SetUIElementValue)- session.queue.put(+ session.control_queue.put(requests.SetUIElementValueRequest(zip(args.object_ids,diff --git a/marimo/_server/api/stdin.py b/marimo/_server/api/stdin.pynew file mode 100644index 0000000000..3c6461d9e7--- /dev/null+++ b/marimo/_server/api/stdin.py@@ -0,0 +1,23 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from dataclasses import dataclass++from marimo._server import sessions+from marimo._server.api.validated_handler import ValidatedHandler+from marimo._utils.parse_dataclass import parse_raw+++@dataclass+class Stdin:+ text: str+++class StdinHandler(ValidatedHandler):+ """Send input to the stdin stream."""++ @sessions.requires_edit+ def post(self) -> None:+ args = parse_raw(self.request.body, Stdin)+ session = sessions.require_session_from_header(self.request.headers)+ session.input_queue.put(args.text)diff --git a/marimo/_server/server.py b/marimo/_server/server.pyindex da2f408c1e..f794b9cd69 100644--- a/marimo/_server/server.py+++ b/marimo/_server/server.py@@ -216,6 +216,10 @@ def construct_app(r"/api/kernel/save_app_config/",api.SaveAppConfigurationHandler,),+ (+ r"/api/kernel/stdin/",+ api.StdinHandler,+ ),(r"/api/kernel/read_code/",api.ReadCodeHandler,diff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.pyindex 178fcd3d94..1b941a5f1e 100644--- a/marimo/_server/sessions.py+++ b/marimo/_server/sessions.py@@ -249,7 +249,16 @@ class Session:mgr = get_manager()self.socket = socket_handlerself.cancel_close_handle: Optional[object] = None- self.queue: mp.Queue[requests.Request] | queue.Queue[requests.Request]++ # Control messages for the kernel (run, autocomplete,+ # set UI element, set config, etc ) are sent through the control queue+ self.control_queue: mp.Queue[requests.Request] | queue.Queue[+ requests.Request+ ]+ # Input messages for the user's Python code are sent through the+ # input queue+ self.input_queue: mp.Queue[str] | queue.Queue[str]+self.kernel_task: threading.Thread | mp.Processself.read_conn: connection.Connection@@ -266,10 +275,17 @@ class Session:# We use a process in edit mode so that we can interrupt the app# with a SIGINT; we don't mind the additional memory consumption,# since there's only one client session- self.queue = mpctx.Queue()+ self.control_queue = mpctx.Queue()+ self.input_queue = mpctx.Queue(maxsize=1)self.kernel_task = mp.Process(target=runtime.launch_kernel,- args=(self.queue, listener.address, is_edit_mode, configs),+ args=(+ self.control_queue,+ self.input_queue,+ listener.address,+ is_edit_mode,+ configs,+ ),# The process can't be a daemon, because daemonic processes# can't create children# https://docs.python.org/3/library/multiprocessing.html#multiprocessing.Process.daemon # noqa: E501@@ -279,7 +295,8 @@ class Session:# We use threads in run mode to minimize memory consumption;# launching a process would copy the entire program state,# which (as of writing) is around 150MB- self.queue = queue.Queue()+ self.control_queue = queue.Queue()+ self.input_queue = queue.Queue(maxsize=1)loop = tornado.ioloop.IOLoop.current()# We can't terminate threads, so we have to wait until they@@ -298,7 +315,13 @@ class Session:# down all client sessionsself.kernel_task = threading.Thread(target=launch_kernel_with_cleanup,- args=(self.queue, listener.address, is_edit_mode, configs),+ args=(+ self.control_queue,+ self.input_queue,+ listener.address,+ is_edit_mode,+ configs,+ ),# daemon threads can create child processes, unlike# daemon processesdaemon=True,@@ -352,10 +375,12 @@ class Session:# guaranteed to be a multiprocessing Queue; annoying to assert# this, because mp.Queue appears to be a function#- # don't care if queue still has things in it; don't make the+ # don't care if the queues still have things in it; don't make the# child process wait for it to empty.- self.queue.cancel_join_thread() # type: ignore- self.queue.close() # type: ignore+ self.control_queue.cancel_join_thread() # type: ignore+ self.control_queue.close() # type: ignore+ self.input_queue.cancel_join_thread() # type: ignore+ self.input_queue.close() # type: ignoreif self.kernel_task.is_alive():# Explicitly terminate the processself.kernel_task.terminate()@@ -366,7 +391,7 @@ class Session:elif self.kernel_task.is_alive():# kernel thread cleans up read/write conn and IOloop handler on# exit; we don't join the thread because we don't want to block- self.queue.put(requests.StopRequest())+ self.control_queue.put(requests.StopRequest())# 1000 - normal closureself.socket.close(1000, "MARIMO_SHUTDOWN")diff --git a/marimo/_smoke_tests/inputs.py b/marimo/_smoke_tests/inputs.pyindex bb543921c5..c96911263b 100644--- a/marimo/_smoke_tests/inputs.py+++ b/marimo/_smoke_tests/inputs.py@@ -1,3 +1,4 @@+# Copyright 2024 Marimo. All rights reserved.import marimo__generated_with = "0.1.77"diff --git a/marimo/_smoke_tests/stdin.py b/marimo/_smoke_tests/stdin.pynew file mode 100644index 0000000000..fdc9fc8eef--- /dev/null+++ b/marimo/_smoke_tests/stdin.py@@ -0,0 +1,38 @@+import marimo++__generated_with = "0.1.77"+app = marimo.App()+++def __():+ import marimo as mo+ return mo,+++def __():+ value = input("what is your name?")+ return value,+++def __(mo, value):+ mo.md(f"## 👋 Hi {value}")+ return+++def __():+ print('hi')+ return+++def __():+ print('there')+ return+++if __name__ == "__main__":+ app.run()diff --git a/tests/_messaging/test_streams.py b/tests/_messaging/test_streams.pynew file mode 100644index 0000000000..5c3f3cfda7--- /dev/null+++ b/tests/_messaging/test_streams.py@@ -0,0 +1,76 @@+from marimo._runtime.runtime import Kernel+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_input_installed(k: Kernel, exec_req: ExecReqProvider) -> None:+ k.run([exec_req.get("output = input('hello')")])+ assert k.globals["output"] == "hello"++ @staticmethod+ def test_readline_installed(k: Kernel, exec_req: ExecReqProvider) -> None:+ k.run([exec_req.get("output = sys.stdin.readline()")])+ assert k.globals["output"] == ""++ @staticmethod+ def test_readlines_installed(k: Kernel, exec_req: ExecReqProvider) -> None:+ k.run([exec_req.get("output = sys.stdin.readlines()")])+ assert k.globals["output"] == [""]+++class TestStdout:+ @staticmethod+ def test_print(+ mocked_kernel: MockedKernel, exec_req: ExecReqProvider+ ) -> None:+ mocked_kernel.k.run([exec_req.get("print('hello'); print('there')")])+ assert mocked_kernel.stdout.messages == ["hello", "\n", "there", "\n"]++ @staticmethod+ def test_write(+ mocked_kernel: MockedKernel, exec_req: ExecReqProvider+ ) -> None:+ mocked_kernel.k.run(+ [exec_req.get("import sys; sys.stdout.write('hello')")]+ )+ assert mocked_kernel.stdout.messages == ["hello"]++ @staticmethod+ def test_writelines(+ mocked_kernel: MockedKernel, exec_req: ExecReqProvider+ ) -> None:+ mocked_kernel.k.run(+ [+ exec_req.get(+ "import sys; sys.stdout.writelines(['hello', 'there'])"+ )+ ]+ )+ assert mocked_kernel.stdout.messages == ["hello", "there"]+++class TestStderr:+ @staticmethod+ def test_write(+ mocked_kernel: MockedKernel, exec_req: ExecReqProvider+ ) -> None:+ mocked_kernel.k.run(+ [exec_req.get("import sys; sys.stderr.write('hello')")]+ )+ assert mocked_kernel.stderr.messages == ["hello"]++ @staticmethod+ def test_writelines(+ mocked_kernel: MockedKernel, exec_req: ExecReqProvider+ ) -> None:+ mocked_kernel.k.run(+ [+ exec_req.get(+ "import sys; sys.stderr.writelines(['hello', 'there'])"+ )+ ]+ )+ assert mocked_kernel.stderr.messages == ["hello", "there"]diff --git a/tests/conftest.py b/tests/conftest.pyindex 3ef86416f9..fbedc529fb 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -8,6 +8,7 @@ from typing import Any, Generatorimport pytestfrom marimo._ast.cell import CellId_t+from marimo._messaging.streams import Stderr, Stdin, Stdoutfrom marimo._runtime.context import (initialize_context,teardown_context,@@ -18,6 +19,8 @@ from marimo._runtime.runtime import Kernel@dataclasses.dataclassclass _MockStream:+ """Captures the ops sent through the stream"""+messages: list[tuple[str, dict[Any, Any]]] = dataclasses.field(default_factory=list)@@ -27,11 +30,33 @@ class _MockStream:@dataclasses.dataclass-class _MockStdStream:+class MockStdout(Stdout):+ """Captures the output sent through the stream"""++ messages: list[str] = dataclasses.field(default_factory=list)++ 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 write(self, msg: str) -> None:- self.messages.append(msg)+ def write(self, data: str) -> int:+ self.messages.append(data)+ return len(data)+++class MockStdin(Stdin):+ """Echoes the prompt."""++ def _readline_with_prompt(self, prompt: str = "") -> str:+ return prompt@dataclasses.dataclass@@ -40,15 +65,17 @@ class MockedKernel:default_factory=lambda: Kernel(cell_configs={}))stream: _MockStream = dataclasses.field(default_factory=_MockStream)- stdout: _MockStdStream = dataclasses.field(default_factory=_MockStdStream)- stderr: _MockStdStream = dataclasses.field(default_factory=_MockStdStream)+ 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:initialize_context(kernel=self.k,stream=self.stream, # type: ignore- stdout=self.stdout, # type: ignore- stderr=self.stderr, # type: ignore+ stdout=self.stdout,+ stderr=self.stderr,+ stdin=self.stdin,)def __del__(self) -> None: