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.

improve: prompt to run in sandbox when appropriate (#2412)

Akshay Agrawal74bd0ebf4187
diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.py
index 3aaa12b59d..b443b24db1 100644
--- a/marimo/_cli/cli.py
+++ b/marimo/_cli/cli.py
@@ -155,6 +155,14 @@ token_password_message = """
show_default=True,
help="Suppress standard out.",
)
+ "-y",
+ "--yes",
+ is_flag=True,
+ default=False,
+ show_default=True,
+ help="Automatic yes to prompts, running non-interactively.",
+)
@click.option(
"-d",
"--development-mode",
@@ -163,12 +171,15 @@ token_password_message = """
show_default=True,
help="Run in development mode; enables debug logs and server autoreload.",
)
-def main(log_level: str, quiet: bool, development_mode: bool) -> None:
+def main(
+ log_level: str, quiet: bool, yes: bool, development_mode: bool
+) -> None:
log_level = "DEBUG" if development_mode else log_level
_loggers.set_level(log_level)
GLOBAL_SETTINGS.DEVELOPMENT_MODE = development_mode
GLOBAL_SETTINGS.QUIET = quiet
+ GLOBAL_SETTINGS.YES = yes
GLOBAL_SETTINGS.LOG_LEVEL = _loggers.log_level_string_to_int(log_level)
@@ -284,7 +295,9 @@ def edit(
name: Optional[str],
args: tuple[str, ...],
) -> None:
- if sandbox:
+ from marimo._cli.sandbox import prompt_run_in_sandbox
+
+ if sandbox or prompt_run_in_sandbox(name):
from marimo._cli.sandbox import run_in_sandbox
run_in_sandbox(sys.argv[1:], name)
@@ -566,7 +579,9 @@ def run(
name: str,
args: tuple[str, ...],
) -> None:
- if sandbox:
+ from marimo._cli.sandbox import prompt_run_in_sandbox
+
+ if sandbox or prompt_run_in_sandbox(name):
from marimo._cli.sandbox import run_in_sandbox
run_in_sandbox(sys.argv[1:], name)
diff --git a/marimo/_cli/config/commands.py b/marimo/_cli/config/commands.py
index 4e9bbe2611..46bcd90362 100644
--- a/marimo/_cli/config/commands.py
+++ b/marimo/_cli/config/commands.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import click
from marimo._cli.config.utils import highlight_toml_headers
-from marimo._cli.print import green
+from marimo._cli.print import echo, green
from marimo._config.manager import UserConfigManager
@@ -24,9 +24,9 @@ def show() -> None:
import tomlkit
config_manager = UserConfigManager()
- click.echo(f"User config from {green(config_manager.get_config_path())}\n")
+ echo(f"User config from {green(config_manager.get_config_path())}\n")
toml_string = tomlkit.dumps(config_manager.get_config())
- click.echo(highlight_toml_headers(toml_string))
+ echo(highlight_toml_headers(toml_string))
config.add_command(show)
diff --git a/marimo/_cli/convert/commands.py b/marimo/_cli/convert/commands.py
index a00eadb1af..7e9b08368a 100644
--- a/marimo/_cli/convert/commands.py
+++ b/marimo/_cli/convert/commands.py
@@ -8,6 +8,7 @@ import click
from marimo._cli.convert.ipynb import convert_from_ipynb
from marimo._cli.convert.markdown import convert_from_md
from marimo._cli.convert.utils import load_external_file
+from marimo._cli.print import echo
@click.argument("filename", required=True)
@@ -47,4 +48,4 @@ def convert(
else:
assert ext in (".md", ".qmd")
notebook = convert_from_md(text)
- click.echo(notebook)
+ echo(notebook)
diff --git a/marimo/_cli/export/commands.py b/marimo/_cli/export/commands.py
index 9107cc2bb9..6117b3a13e 100644
--- a/marimo/_cli/export/commands.py
+++ b/marimo/_cli/export/commands.py
@@ -8,7 +8,7 @@ from typing import TYPE_CHECKING, Callable
import click
from marimo._cli.parse_args import parse_args
-from marimo._cli.print import green
+from marimo._cli.print import echo, green
from marimo._server.export import (
export_as_ipynb,
export_as_md,
@@ -49,7 +49,7 @@ def watch_and_export(
f.write(data)
f.close()
else:
- click.echo(data)
+ echo(data)
return
# No watch, just run once
@@ -59,18 +59,14 @@ def watch_and_export(
return
async def on_file_changed(file_path: Path) -> None:
- click.echo(
- f"File {str(file_path)} changed. Re-exporting to {green(output)}"
- )
+ echo(f"File {str(file_path)} changed. Re-exporting to {green(output)}")
data = export_callback(MarimoPath(file_path))
write_data(data)
async def start() -> None:
# Watch the file for changes
watcher = FileWatcher.create(marimo_path.path, on_file_changed)
- click.echo(
- f"Watching {green(marimo_path.relative_name)} for changes..."
- )
+ echo(f"Watching {green(marimo_path.relative_name)} for changes...")
watcher.start()
try:
# Run forever
diff --git a/marimo/_cli/print.py b/marimo/_cli/print.py
index 27873474a8..6e18a7cb74 100644
--- a/marimo/_cli/print.py
+++ b/marimo/_cli/print.py
@@ -2,16 +2,36 @@
from __future__ import annotations
+from typing import Any
+
+from marimo._config.settings import GLOBAL_SETTINGS
+
# Print helpers
-def green(text: str) -> str:
- return "\033[32m" + text + "\033[0m"
+def bold(text: str) -> str:
+ return "\033[1m" + text + "\033[0m"
+
+
+def green(text: str, bold: bool = False) -> str:
+ prefix = "\033[32m" if not bold else "\033[1;32m"
+ return prefix + text + "\033[0m"
+
+
+def orange(text: str, bold: bool = False) -> str:
+ prefix = "\033[33m" if not bold else "\033[1;33m"
+ return prefix + text + "\033[0m"
+
+
+def red(text: str, bold: bool = False) -> str:
+ prefix = "\033[31m" if not bold else "\033[1;31m"
+ return prefix + text + "\033[0m"
-def orange(text: str) -> str:
- return "\033[33m" + text + "\033[0m"
+def echo(*args: Any, **kwargs: Any) -> None:
+ import click
+ if GLOBAL_SETTINGS.QUIET:
+ return
-def red(text: str) -> str:
- return "\033[31m" + text + "\033[0m"
+ click.echo(*args, **kwargs)
diff --git a/marimo/_cli/sandbox.py b/marimo/_cli/sandbox.py
index 2e925ae7cc..dcb8ee1e4a 100644
--- a/marimo/_cli/sandbox.py
+++ b/marimo/_cli/sandbox.py
@@ -13,6 +13,8 @@ from typing import Any, Dict, List, Optional, cast
import click
from marimo import _loggers
+from marimo._cli.print import bold, echo, green
+from marimo._config.settings import GLOBAL_SETTINGS
from marimo._dependencies.dependencies import DependencyManager
LOGGER = _loggers.marimo_logger()
@@ -22,6 +24,82 @@ REGEX = (
)
+def _get_dependencies(script: str) -> List[str] | None:
+ """Get dependencies from string representation of script"""
+ try:
+ pyproject = _read_pyproject(script) or {}
+ return cast(List[str], pyproject.get("dependencies", []))
+ except Exception as e:
+ LOGGER.warning(f"Failed to parse dependencies: {e}")
+ return None
+
+
+def get_dependencies_from_filename(name: str) -> List[str]:
+ if os.path.isfile(name):
+ with open(name) as f:
+ dependencies = _get_dependencies(f.read())
+ return dependencies if dependencies is not None else []
+ return []
+
+
+def _read_pyproject(script: str) -> Dict[str, Any] | None:
+ """
+ Read the pyproject.toml file from the script.
+
+ Adapted from https://peps.python.org/pep-0723/#reference-implementation
+ """
+ name = "script"
+ matches = list(
+ filter(lambda m: m.group("type") == name, re.finditer(REGEX, script))
+ )
+ if len(matches) > 1:
+ raise ValueError(f"Multiple {name} blocks found")
+ elif len(matches) == 1:
+ content = "".join(
+ line[2:] if line.startswith("# ") else line[1:]
+ for line in matches[0].group("content").splitlines(keepends=True)
+ )
+ import tomlkit
+
+ return tomlkit.parse(content)
+ else:
+ return None
+
+
+def prompt_run_in_sandbox(name: str | None) -> bool:
+ if name is None:
+ return False
+
+ dependencies = get_dependencies_from_filename(name)
+ if not dependencies:
+ return False
+
+ # Notebook has inlined dependencies.
+ if DependencyManager.which("uv"):
+ if GLOBAL_SETTINGS.YES:
+ return True
+
+ return click.confirm(
+ "This notebook has inlined package dependencies.\n"
+ + green(
+ "Run in a sandboxed venv containing this notebook's "
+ "dependencies?",
+ bold=True,
+ ),
+ default=True,
+ )
+ else:
+ echo(
+ bold(
+ "This notebook has inlined package dependencies. \n"
+ + "Consider installing uv so that marimo can create a "
+ "temporary venv with the notebook's packages: "
+ "https://github.com/astral-sh/uv"
+ )
+ )
+ return False
+
+
def run_in_sandbox(
args: List[str],
name: Optional[str] = None,
@@ -30,13 +108,13 @@ def run_in_sandbox(
raise click.UsageError("uv must be installed to use --sandbox")
cmd = ["marimo"] + args
- cmd.remove("--sandbox")
+ if "--sandbox" in cmd:
+ cmd.remove("--sandbox")
# If name if a filepath, parse the dependencies from the file
- dependencies = []
- if name is not None and os.path.isfile(name):
- with open(name) as f:
- dependencies = _get_dependencies(f.read()) or []
+ dependencies = (
+ get_dependencies_from_filename(name) if name is not None else []
+ )
# The sandbox needs to manage marimo, too, to make sure
# that the outer environment doesn't leak into the sandbox.
@@ -62,7 +140,7 @@ def run_in_sandbox(
temp_file_path,
] + cmd
- click.echo(f"Running in a sandbox: {' '.join(cmd)}")
+ echo(f"Running in a sandbox: {' '.join(cmd)}")
env = os.environ.copy()
env["MARIMO_MANAGE_SCRIPT_METADATA"] = "true"
@@ -80,36 +158,3 @@ def run_in_sandbox(
signal.signal(signal.SIGINT, handler)
return process.wait()
-
-
-def _get_dependencies(script: str) -> List[str] | None:
- try:
- pyproject = _read_pyproject(script) or {}
- return cast(List[str], pyproject.get("dependencies", []))
- except Exception as e:
- LOGGER.warning(f"Failed to parse dependencies: {e}")
- return None
-
-
-def _read_pyproject(script: str) -> Dict[str, Any] | None:
- """
- Read the pyproject.toml file from the script.
-
- Adapted from https://peps.python.org/pep-0723/#reference-implementation
- """
- name = "script"
- matches = list(
- filter(lambda m: m.group("type") == name, re.finditer(REGEX, script))
- )
- if len(matches) > 1:
- raise ValueError(f"Multiple {name} blocks found")
- elif len(matches) == 1:
- content = "".join(
- line[2:] if line.startswith("# ") else line[1:]
- for line in matches[0].group("content").splitlines(keepends=True)
- )
- import tomlkit
-
- return tomlkit.parse(content)
- else:
- return None
diff --git a/marimo/_cli/upgrade.py b/marimo/_cli/upgrade.py
index ee3d8a2aaa..6fbbf5ab2e 100644
--- a/marimo/_cli/upgrade.py
+++ b/marimo/_cli/upgrade.py
@@ -11,7 +11,7 @@ from typing import Any, Callable, Dict, Optional
from packaging import version
from marimo import __version__ as current_version
-from marimo._cli.print import green, orange
+from marimo._cli.print import echo, green, orange
from marimo._server.api.status import HTTPException
from marimo._tracer import server_tracer
from marimo._utils.config.config import ConfigReader
@@ -27,9 +27,9 @@ class MarimoCLIState:
def print_latest_version(current_version: str, latest_version: str) -> None:
message = f"Update available {current_version} → {latest_version}"
- print(orange(message))
- print(f"Run {green('pip install --upgrade marimo')} to upgrade.")
- print()
+ echo(orange(message))
+ echo(f"Run {green('pip install --upgrade marimo')} to upgrade.")
+ echo()
@server_tracer.start_as_current_span("check_for_updates")
diff --git a/marimo/_config/settings.py b/marimo/_config/settings.py
index 9dda3c855b..27e905dc0a 100644
--- a/marimo/_config/settings.py
+++ b/marimo/_config/settings.py
@@ -10,6 +10,7 @@ from dataclasses import dataclass
class GlobalSettings:
DEVELOPMENT_MODE: bool = False
QUIET: bool = False
+ YES: bool = False
CHECK_STATUS_UPDATE: bool = False
TRACING: bool = os.getenv("MARIMO_TRACING", "false") in ("true", "1")
PROFILE_DIR: str | None = None
diff --git a/marimo/_server/api/interrupt.py b/marimo/_server/api/interrupt.py
index de2fb4b780..6ca3ca3cb5 100644
--- a/marimo/_server/api/interrupt.py
+++ b/marimo/_server/api/interrupt.py
@@ -5,6 +5,7 @@ import asyncio
import signal
from typing import Callable
+from marimo._config.settings import GLOBAL_SETTINGS
from marimo._server.utils import (
TAB,
)
@@ -53,6 +54,10 @@ class InterruptHandler:
self.shutdown()
try:
+ if GLOBAL_SETTINGS.YES:
+ self.shutdown()
+ return
+
response = input(
f"\r{TAB}\033[1;32mAre you sure you want to quit?\033[0m "
"\033[1m(y/n)\033[0m: "
diff --git a/pyproject.toml b/pyproject.toml
index 52b67888c2..2493be12c9 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -177,6 +177,7 @@ exclude = [
"tests/_ast/app_data",
"tests/_ast/codegen_data",
"tests/_ast/cell_data",
+ "tests/_cli/cli_data",
"tests/_cli/ipynb_data",
"tests/_runtime/runtime_data",
"tests/_ast/test_app.py",
@@ -282,6 +283,7 @@ exclude = [
'tests/_ast/app_data',
'tests/_ast/codegen_data',
'tests/_ast/cell_data',
+ 'tests/_cli/cli_data',
'tests/_cli/ipynb_data',
'tests/_runtime/runtime_data',
'marimo/_tutorials/',
diff --git a/tests/_cli/cli_data/sandbox.py b/tests/_cli/cli_data/sandbox.py
new file mode 100644
index 0000000000..1d99a2fd14
--- /dev/null
+++ b/tests/_cli/cli_data/sandbox.py
@@ -0,0 +1,22 @@
+# /// script
+# requires-python = ">=3.12"
+# dependencies = [
+# "marimo",
+# ]
+# ///
+
+import marimo
+
+__generated_with = "0.8.20"
+app = marimo.App()
+
+
+def __():
+ import marimo as mo
+
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_cli/test_cli.py b/tests/_cli/test_cli.py
index 7623dc52a6..be81dac61d 100644
--- a/tests/_cli/test_cli.py
+++ b/tests/_cli/test_cli.py
@@ -29,6 +29,8 @@ from marimo._utils.config.config import ROOT_DIR as CONFIG_ROOT_DIR
HAS_UV = DependencyManager.which("uv")
+DIR_PATH = os.path.dirname(os.path.realpath(__file__))
+
def _is_win32() -> bool:
return sys.platform == "win32"
@@ -594,6 +596,7 @@ def test_cli_edit_shutdown() -> None:
with _patch_signals_win32():
_interrupt(p)
assert p.poll() is None
+
assert p.stdin is not None
_confirm_shutdown(p)
_check_shutdown(p)
@@ -617,3 +620,93 @@ def test_cli_run_shutdown() -> None:
p.stdin.flush()
time.sleep(3)
assert p.poll() == 0
+
+
+def test_cli_edit_sandbox_prompt() -> None:
+ port = _get_port()
+ path = os.path.join(DIR_PATH, "cli_data", "sandbox.py")
+ p = subprocess.Popen(
+ [
+ "marimo",
+ "edit",
+ path,
+ "--headless",
+ "--no-token",
+ "--skip-update-check",
+ "-p",
+ str(port),
+ ],
+ stdin=subprocess.PIPE,
+ )
+ assert p.poll() is None
+ assert p.stdin is not None
+ p.stdin.write(b"y\n")
+ p.stdin.flush()
+ _check_started(port)
+ p.kill()
+
+
+def test_cli_run_sandbox_prompt() -> None:
+ port = _get_port()
+ path = os.path.join(DIR_PATH, "cli_data", "sandbox.py")
+ p = subprocess.Popen(
+ [
+ "marimo",
+ "run",
+ path,
+ "--headless",
+ "--no-token",
+ "-p",
+ str(port),
+ ],
+ stdin=subprocess.PIPE,
+ )
+ assert p.poll() is None
+ assert p.stdin is not None
+ p.stdin.write(b"y\n")
+ p.stdin.flush()
+ _check_started(port)
+ p.kill()
+
+
[email protected](reason="Need to release -y to PyPI")
+def test_cli_edit_sandbox_prompt_yes() -> None:
+ port = _get_port()
+ path = os.path.join(DIR_PATH, "cli_data", "sandbox.py")
+ p = subprocess.Popen(
+ [
+ "marimo",
+ "-y",
+ "edit",
+ path,
+ "--headless",
+ "--no-token",
+ "--skip-update-check",
+ "-p",
+ str(port),
+ ],
+ )
+ assert p.poll() is None
+ _check_started(port)
+ p.kill()
+
+
[email protected](reason="Need to release -y to PyPI")
+def test_cli_run_sandbox_prompt_yes() -> None:
+ port = _get_port()
+ path = os.path.join(DIR_PATH, "cli_data", "sandbox.py")
+ p = subprocess.Popen(
+ [
+ "marimo",
+ "-y",
+ "run",
+ path,
+ "--headless",
+ "--no-token",
+ "-p",
+ str(port),
+ ],
+ )
+ assert p.poll() is None
+ _check_started(port)
+ p.kill()
diff --git a/tests/_cli/test_upgrade.py b/tests/_cli/test_upgrade.py
index 4c694da428..eed4d57163 100644
--- a/tests/_cli/test_upgrade.py
+++ b/tests/_cli/test_upgrade.py
@@ -21,9 +21,9 @@ from marimo._cli.upgrade import (
new_callable=mock_open,
)
@patch("marimo._cli.upgrade._update_with_latest_version")
-@patch("builtins.print")
+@patch("marimo._cli.upgrade.echo")
def test_check_for_updates(
- mock_print: Any,
+ mock_echo: Any,
mock_update_with_latest_version: Any,
mock_open_file: Any,
mock_makedirs: Any,
@@ -42,13 +42,15 @@ def test_check_for_updates(
# Assert that the makedirs function was not called
mock_makedirs.assert_not_called()
+ mock_echo.assert_called()
+
# Assert prints
assert any(
- "0.1.0 → 0.1.2" in call[0][0] for call in mock_print.call_args_list
+ "0.1.0 → 0.1.2" in call[0][0] for call in mock_echo.call_args_list
)
assert any(
"pip install --upgrade marimo" in call[0][0]
- for call in mock_print.call_args_list
+ for call in mock_echo.call_args_list
)