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
Add mo.output.clear_console() (#9950)
Shahmir Varqhafb0ae6632601
diff --git a/docs/api/outputs.md b/docs/api/outputs.mdindex ee442edffc..cab89a0e34 100644--- a/docs/api/outputs.md+++ b/docs/api/outputs.md@@ -46,6 +46,8 @@ as an app. If you do want them to appear in apps, marimo provides utilityfunctions for capturing console outputs and redirecting them to cell outputs.///+::: marimo.output.clear_console+::: marimo.redirect_stdout::: marimo.redirect_stderrdiff --git a/frontend/src/components/editor/connections/components.tsx b/frontend/src/components/editor/connections/components.tsxindex 1f6dcbb168..96bcfd44ae 100644--- a/frontend/src/components/editor/connections/components.tsx+++ b/frontend/src/components/editor/connections/components.tsx@@ -1,6 +1,7 @@/* Copyright 2026 Marimo. All rights reserved. */import { zodResolver } from "@hookform/resolvers/zod";+import { useAtomValue } from "jotai";import React from "react";import { type DefaultValues, type FieldValues, useForm } from "react-hook-form";import type { z } from "zod";@@ -16,8 +17,10 @@ import {SelectTrigger,SelectValue,} from "@/components/ui/select";+import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";import { useCellActions } from "@/core/cells/cells";import { useLastFocusedCellId } from "@/core/cells/focus";+import { autoInstantiateAtom } from "@/core/config/config";import { ENV_RENDERER, SecretsProvider } from "./form-renderers";const RENDERERS: FormRenderer[] = [ENV_RENDERER];@@ -106,8 +109,18 @@ export const ConnectionFormFooter = <L extends string>({export function useInsertCode() {const { createNewCell } = useCellActions();const lastFocusedCellId = useLastFocusedCellId();+ const autoInstantiate = useAtomValue(autoInstantiateAtom);return (code: string) => {+ // Ensure `mo` is importable when the generated code references it+ if (/\bmo\./.test(code)) {+ maybeAddMarimoImport({+ autoInstantiate,+ createNewCell,+ fromCellId: lastFocusedCellId,+ });+ }+createNewCell({code,before: false,diff --git a/frontend/src/components/editor/connections/storage/__tests__/__snapshots__/as-code.test.ts.snap b/frontend/src/components/editor/connections/storage/__tests__/__snapshots__/as-code.test.ts.snapindex 59121833fd..9cdd758d8c 100644--- a/frontend/src/components/editor/connections/storage/__tests__/__snapshots__/as-code.test.ts.snap+++ b/frontend/src/components/editor/connections/storage/__tests__/__snapshots__/as-code.test.ts.snap@@ -85,14 +85,14 @@ store = GCSStore("my-bucket")"exports[`generateStorageCode > Google Drive > with default auth (no credentials) 1`] = `"from gdrive_fsspec import GoogleDriveFileSystem-fs = GoogleDriveFileSystem(use_listings_cache=False)"+fs = GoogleDriveFileSystem(use_listings_cache=False, skip_instance_cache=True)"`;exports[`generateStorageCode > Google Drive > with embedded auth (no credentials) 1`] = `"from gdrive_fsspec import GoogleDriveFileSystem-fs = GoogleDriveFileSystem(use_listings_cache=False, auth_kwargs={"use_local_webserver": False})-print("Google Drive connected! Important: Run this cell again to clear the console")"+fs = GoogleDriveFileSystem(use_listings_cache=False, skip_instance_cache=True, auth_kwargs={"use_local_webserver": False})+mo.output.clear_console()"`;exports[`generateStorageCode > Google Drive > with service account credentials 1`] = `@@ -100,7 +100,7 @@ exports[`generateStorageCode > Google Drive > with service account credentials 1import json_creds = json.loads("""{"type": "service_account", "client_email": "[email protected]"}""")-fs = GoogleDriveFileSystem(creds=_creds, token="service_account", use_listings_cache=False)"+fs = GoogleDriveFileSystem(creds=_creds, token="service_account", use_listings_cache=False, skip_instance_cache=True)"`;exports[`generateStorageCode > S3 > basic connection with all fields 1`] = `diff --git a/frontend/src/components/editor/connections/storage/as-code.ts b/frontend/src/components/editor/connections/storage/as-code.tsindex c5fa6b58ba..142f79158d 100644--- a/frontend/src/components/editor/connections/storage/as-code.ts+++ b/frontend/src/components/editor/connections/storage/as-code.ts@@ -168,6 +168,10 @@ function generateGDriveCode(connection: Extract<StorageConnection, { type: "gdrive" }>,options: { secrets: SecretContainer; isEmbedded?: boolean },): { imports: Set<string>; code: string } {+ /**+ * Skip instance cache True so you can create multiple connections which don't reference the same creds.+ * Use listings cache False so we don't get stale reads.+ */const { secrets, isEmbedded = false } = options;const imports = new Set(["from gdrive_fsspec import GoogleDriveFileSystem"]);@@ -179,18 +183,21 @@ function generateGDriveCode();const code = dedent(`_creds = json.loads("""${connection.credentials_json?.startsWith("ENV:") ? `{${creds}}` : connection.credentials_json}""")- fs = GoogleDriveFileSystem(creds=_creds, token="service_account", use_listings_cache=False)+ fs = GoogleDriveFileSystem(creds=_creds, token="service_account", use_listings_cache=False, skip_instance_cache=True)`);return { imports, code };}+ // In the iframe (embedded) flow we authenticate via the console-based OOB+ // flow, which prints an auth URL and reads the code from stdin. Clear the+ // console afterwards so the (single-use) auth code doesn't linger.const code = isEmbedded? dedent(`- fs = GoogleDriveFileSystem(use_listings_cache=False, auth_kwargs={"use_local_webserver": False})- print("Google Drive connected! Important: Run this cell again to clear the console")+ fs = GoogleDriveFileSystem(use_listings_cache=False, skip_instance_cache=True, auth_kwargs={"use_local_webserver": False})+ mo.output.clear_console()`): dedent(`- fs = GoogleDriveFileSystem(use_listings_cache=False)+ fs = GoogleDriveFileSystem(use_listings_cache=False, skip_instance_cache=True)`);return { imports, code };}diff --git a/marimo/_runtime/output/__init__.py b/marimo/_runtime/output/__init__.pyindex 735e193e75..29920752d8 100644--- a/marimo/_runtime/output/__init__.py+++ b/marimo/_runtime/output/__init__.py@@ -4,6 +4,7 @@__all__ = ["append","clear",+ "clear_console","replace","replace_at_index",]@@ -11,6 +12,7 @@ __all__ = [from marimo._runtime.output._output import (append,clear,+ clear_console,replace,replace_at_index,)diff --git a/marimo/_runtime/output/_output.py b/marimo/_runtime/output/_output.pyindex e9ad75b93b..a8ed031c01 100644--- a/marimo/_runtime/output/_output.py+++ b/marimo/_runtime/output/_output.py@@ -2,7 +2,11 @@from __future__ import annotationsfrom marimo._messaging.cell_output import CellChannel-from marimo._messaging.notification_utils import CellNotificationUtils+from marimo._messaging.notification import CellNotification+from marimo._messaging.notification_utils import (+ CellNotificationUtils,+ broadcast_notification,+)from marimo._messaging.tracebacks import write_tracebackfrom marimo._output import formattingfrom marimo._output.rich_help import mddoc@@ -135,3 +139,27 @@ def remove(value: object) -> None:output = ctx.execution_context.outputoutput.remove(value)flush()+++@mddoc+def clear_console() -> None:+ """Clear a cell's console output.++ Call `mo.output.clear_console()` to clear the console output area below a+ cell, including text written earlier in the same run (via `print`, logging,+ or `stdout`/`stderr`).+ """+ try:+ ctx = get_context()+ except ContextNotInitializedError:+ return++ if ctx.execution_context is None:+ return++ ctx.stream.flush_console()+ if ctx.stream.cell_id is not None:+ broadcast_notification(+ CellNotification(cell_id=ctx.stream.cell_id, console=[]),+ stream=ctx.stream,+ )diff --git a/marimo/_session/state/session_view.py b/marimo/_session/state/session_view.pyindex 0758035cc1..894b00483e 100644--- a/marimo/_session/state/session_view.py+++ b/marimo/_session/state/session_view.py@@ -644,8 +644,14 @@ def merge_cell_notification(if current.status is None:current.status = previous.status- # If we went from queued to running, clear the console.- if current.status == "running" and previous.status == "queued":+ # Reset the console on an explicit empty list (the `[]` clears contract,+ # e.g. mo.output.clear_console()) or on queued -> running. Otherwise stale+ # console output would persist in the session view.+ explicit_clear = isinstance(current.console, list) and not current.console+ queued_to_running = (+ current.status == "running" and previous.status == "queued"+ )+ if explicit_clear or queued_to_running:current.console = []else:combined_console: list[CellOutput] = as_list(previous.console)diff --git a/tests/_runtime/output/test_output.py b/tests/_runtime/output/test_output.pyindex 0ab3429a1a..a8ab47deac 100644--- a/tests/_runtime/output/test_output.py+++ b/tests/_runtime/output/test_output.py@@ -90,6 +90,33 @@ async def test_nested_output(assert outputs[0] == "['hi', [...], [...], [...], [...], [...]]"+async def test_clear_console(+ mocked_kernel: MockedKernel, exec_req: ExecReqProvider+) -> None:+ await mocked_kernel.k.run(+ [+ exec_req.get(+ """+ import marimo as mo++ print("secret")+ mo.output.clear_console()+ """+ )+ ]+ )++ # `clear_console()` broadcasts an explicit console clear (empty list) with+ # no status transition; the running-status clear instead carries+ # status="running", so filtering on status=None isolates our emission.+ clears = [+ msg+ for msg in mocked_kernel.stream.cell_notifications+ if msg.console == [] and msg.status is None+ ]+ assert len(clears) == 1++def test_without_context():from marimo._runtime.context import get_contextfrom marimo._runtime.context.types import ContextNotInitializedError@@ -104,4 +131,5 @@ def test_without_context():output.replace_at_index("test", 0)output.append("test")output.clear()+ output.clear_console()assert True # No exceptions should be raiseddiff --git a/tests/_session/state/test_session_view.py b/tests/_session/state/test_session_view.pyindex 679c7ab580..aed92ad19b 100644--- a/tests/_session/state/test_session_view.py+++ b/tests/_session/state/test_session_view.py@@ -1100,6 +1100,51 @@ def test_combine_console_outputs(]+@patch("time.time", return_value=123)+def test_explicit_empty_console_clears_mid_run(+ time_mock: Any, session_view: SessionView+) -> None:+ """An explicit `console=[]` clears the session view, even while running."""+ del time_mock+ session_view.add_notification(+ CellNotification(+ cell_id=cell_id,+ console=CellOutput.stdout("secret"),+ status="running",+ )+ )+ session_view.add_notification(+ CellNotification(+ cell_id=cell_id,+ console=CellOutput.stdout(" code"),+ status="running",+ )+ )+ assert session_view.cell_notifications[cell_id].console == [+ CellOutput.stdout("secret code"),+ ]++ # Explicit clear mid-run (status stays "running", no queued transition).+ session_view.add_notification(+ CellNotification(+ cell_id=cell_id,+ console=[],+ status="running",+ )+ )+ assert session_view.cell_notifications[cell_id].console == []++ # A subsequent status-only update (console unchanged) keeps it cleared.+ session_view.add_notification(+ CellNotification(+ cell_id=cell_id,+ console=None,+ status="running",+ )+ )+ assert session_view.cell_notifications[cell_id].console == []++@patch("time.time", return_value=123)def test_stdin(time_mock: Any, session_view: SessionView) -> None:del time_mockdiff --git a/tests/snapshots/api.txt b/tests/snapshots/api.txtindex f77a695603..c12212597e 100644--- a/tests/snapshots/api.txt+++ b/tests/snapshots/api.txt@@ -57,6 +57,7 @@ outlineoutputappendclear+ clear_consolereplacereplace_at_index