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.

improvement: add --include-code to marimo run (#463)

Myles Scolnick73aea23d88f6
diff --git a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx
index ec815f086b..6e6567c17f 100644
--- a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx
+++ b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx
@@ -1,5 +1,5 @@
/* Copyright 2023 Marimo. All rights reserved. */
-import { memo, useRef, useState } from "react";
+import React, { memo, useRef, useState } from "react";
import { CellRuntimeState } from "@/core/cells/types";
import { CellId, HTMLCellId } from "@/core/cells/ids";
import { OutputArea } from "@/components/editor/Output";
@@ -13,6 +13,7 @@ import { Code2Icon } from "lucide-react";
import { cn } from "@/utils/cn";
import { Button } from "@/components/ui/button";
import { outputIsStale } from "@/core/cells/cell";
+import { isStaticNotebook } from "@/core/static/static-state";
type VerticalLayout = null;
type VerticalLayoutProps = ICellRendererProps<VerticalLayout>;
@@ -44,7 +45,15 @@ const VerticalLayoutRenderer: React.FC<VerticalLayoutProps> = ({
/>
))}
{canShowCode && (
- <div className="absolute m-4 left-0 top-0">
+ <div
+ className={cn(
+ "right-0 top-0 z-10 m-4",
+ // If the notebook is static, we have a banner at the top, so
+ // we can't use fixed positioning. Ideally this is sticky, but the
+ // current dom structure makes that difficult.
+ isStaticNotebook() ? "absolute" : "fixed"
+ )}
+ >
<Button
variant="secondary"
onClick={() => setShowCode((prev) => !prev)}
diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.py
index eb9add89e5..f4b7541bbc 100644
--- a/marimo/_cli/cli.py
+++ b/marimo/_cli/cli.py
@@ -213,6 +213,7 @@ def edit(
headless=headless,
filename=name,
run=False,
+ include_code=True,
)
)
@@ -244,8 +245,18 @@ Example:
type=bool,
help="Don't launch a browser.",
)
+ "--include-code",
+ is_flag=True,
+ default=False,
+ show_default=True,
+ type=bool,
+ help="Include notebook code in the app.",
+)
@click.argument("name", required=True)
-def run(port: Optional[int], headless: bool, name: str) -> None:
+def run(
+ port: Optional[int], headless: bool, include_code: bool, name: str
+) -> None:
# Validate name, or download from URL
# The second return value is an optional temporary directory. It is unused,
# but must be kept around because its lifetime on disk is bound to the life
@@ -263,6 +274,7 @@ def run(port: Optional[int], headless: bool, name: str) -> None:
headless=headless,
filename=name,
run=True,
+ include_code=include_code,
)
)
@@ -373,6 +385,7 @@ def tutorial(
headless=headless,
filename=fname,
run=False,
+ include_code=True,
)
)
diff --git a/marimo/_cli/test_cli.py b/marimo/_cli/test_cli.py
index ba6f3bb499..abfbc0715a 100644
--- a/marimo/_cli/test_cli.py
+++ b/marimo/_cli/test_cli.py
@@ -99,6 +99,34 @@ def test_cli_run() -> None:
)
+def test_cli_run_with_show_code() -> None:
+ filecontents = codegen.generate_filecontents(
+ ["import marimo as mo"], ["one"], cell_configs=[CellConfig()]
+ )
+ d = tempfile.TemporaryDirectory()
+ path = os.path.join(d.name, "run.py")
+ with open(path, "w", encoding="utf-8") as f:
+ f.write(filecontents)
+
+ port = _get_port()
+ p = subprocess.Popen(
+ [
+ "marimo",
+ "run",
+ path,
+ "-p",
+ str(port),
+ "--headless",
+ "--include-code",
+ ]
+ )
+ contents = _try_fetch(port)
+ _check_contents(p, b"marimo-mode data-mode=read", contents)
+ _check_contents(
+ p, f"marimo-version data-version={__version__}".encode(), contents
+ )
+
+
def test_cli_tutorial() -> None:
port = _get_port()
p = subprocess.Popen(
diff --git a/marimo/_server/server.py b/marimo/_server/server.py
index 0661db454e..da2f408c1e 100644
--- a/marimo/_server/server.py
+++ b/marimo/_server/server.py
@@ -307,6 +307,7 @@ async def start_server(
run: bool = False,
development_mode: bool = False,
quiet: bool = False,
+ include_code: bool = False,
) -> None:
"""Start the server.
@@ -318,6 +319,7 @@ async def start_server(
run: if True, starts the server in run (read-only) mode; if False, runs
in edit (read-write) mode.
development_mode: if True, enables tornado debug logging and autoreloading
+ include_code: if True, return the code to the frontend when in run mode
"""
initialize_mimetypes()
@@ -337,6 +339,7 @@ async def start_server(
port=port,
development_mode=development_mode,
quiet=quiet,
+ include_code=include_code,
)
try:
diff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.py
index 347e69be1a..52a89ff942 100644
--- a/marimo/_server/sessions.py
+++ b/marimo/_server/sessions.py
@@ -113,7 +113,7 @@ class IOSocketHandler(tornado.websocket.WebSocketHandler):
codes = ("",)
names = ("__",)
configs = (CellConfig(),)
- elif mgr.mode == SessionMode.EDIT:
+ elif mgr.should_send_code_to_frontend():
codes, names, configs = tuple(
zip(
*tuple(
@@ -392,6 +392,7 @@ class SessionManager:
port: int,
development_mode: bool,
quiet: bool,
+ include_code: bool,
) -> None:
self.filename = filename
self.mode = mode
@@ -402,6 +403,7 @@ class SessionManager:
self.quiet = quiet
self.sessions: dict[str, Session] = {}
self.app_config: Optional[_AppConfig]
+ self.include_code = include_code
# token uniquely identifying this server
if (app := self.load_app()) is not None:
@@ -534,6 +536,10 @@ class SessionManager:
if self.lsp_process is not None:
self.lsp_process.terminate()
+ def should_send_code_to_frontend(self) -> bool:
+ """Returns True if the server can send messages to the frontend."""
+ return self.mode == SessionMode.EDIT or self.include_code
+
def requires_edit(handler: Callable[..., Any]) -> Callable[..., Any]:
"""Mark a function as requiring edit permissions.
@@ -559,6 +565,7 @@ def initialize_manager(
port: int,
development_mode: bool,
quiet: bool,
+ include_code: bool,
) -> SessionManager:
"""Must be called on server start."""
global SESSION_MANAGER
@@ -568,6 +575,7 @@ def initialize_manager(
port=port,
development_mode=development_mode,
quiet=quiet,
+ include_code=include_code,
)
return SESSION_MANAGER