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.

feat: respect Python version from inline-scripts (PEP 723) when running with --sandbox (#3122)

devin-ai-integration[bot]ddf8562386ce
diff --git a/marimo/_cli/sandbox.py b/marimo/_cli/sandbox.py
index 5aced145de..dfe6a5b0bf 100644
--- a/marimo/_cli/sandbox.py
+++ b/marimo/_cli/sandbox.py
@@ -135,11 +135,29 @@ def _read_pyproject(script: str) -> Dict[str, Any] | None:
)
import tomlkit
- return tomlkit.parse(content)
+ pyproject = tomlkit.parse(content)
+
+ return pyproject
else:
return None
+def _get_python_version_requirement(pyproject: Dict[str, Any]) -> str | None:
+ """Extract Python version requirement from pyproject metadata."""
+ if pyproject is None:
+ return None
+
+ try:
+ version = pyproject.get("requires-python")
+ # Only return string version requirements
+ if not isinstance(version, str):
+ return None
+ return version
+ except Exception as e:
+ LOGGER.warning(f"Failed to parse Python version requirement: {e}")
+ return None
+
+
def prompt_run_in_sandbox(name: str | None) -> bool:
if GLOBAL_SETTINGS.MANAGE_SCRIPT_METADATA:
return False
@@ -221,7 +239,20 @@ def run_in_sandbox(
# Clean up the temporary file after the subprocess has run
atexit.register(lambda: os.unlink(temp_file_path))
- cmd = [
+ # Get Python version requirement if available
+ if name is not None:
+ contents, _ = FileContentReader().read_file(name)
+ pyproject = _read_pyproject(contents)
+ python_version = (
+ _get_python_version_requirement(pyproject)
+ if pyproject is not None
+ else None
+ )
+ else:
+ python_version = None
+
+ # Construct base UV command
+ uv_cmd = [
"uv",
"run",
"--isolated",
@@ -230,14 +261,21 @@ def run_in_sandbox(
"--no-project",
"--with-requirements",
temp_file_path,
- ] + cmd
+ ]
+
+ # Add Python version if specified
+ if python_version:
+ uv_cmd.extend(["--python", python_version])
+
+ # Final command assembly
+ uv_cmd = uv_cmd + cmd
- echo(f"Running in a sandbox: {muted(' '.join(cmd))}")
+ echo(f"Running in a sandbox: {muted(' '.join(uv_cmd))}")
env = os.environ.copy()
env["MARIMO_MANAGE_SCRIPT_METADATA"] = "true"
- process = subprocess.Popen(cmd, env=env)
+ process = subprocess.Popen(uv_cmd, env=env)
def handler(sig: int, frame: Any) -> None:
del sig
diff --git a/tests/_cli/test_cli.py b/tests/_cli/test_cli.py
index a7bb461c57..cebfc4a46f 100644
--- a/tests/_cli/test_cli.py
+++ b/tests/_cli/test_cli.py
@@ -8,6 +8,7 @@ Requires frontend to be built
from __future__ import annotations
import contextlib
+import inspect
import os
import signal
import socket
@@ -17,7 +18,7 @@ import tempfile
import time
import urllib.error
import urllib.request
-from typing import Any, Callable, Iterator, Optional
+from typing import Any, Callable, Generator, Iterator, Optional
import pytest
@@ -150,6 +151,43 @@ def _read_toml(filepath: str) -> Optional[dict]:
return tomlkit.parse(file.read())
+def temp_marimo_file_with_inline_metadata() -> Generator[str, None, None]:
+ tmp_dir = tempfile.TemporaryDirectory()
+ tmp_file = os.path.join(tmp_dir.name, "notebook.py")
+ content = inspect.cleandoc(
+ """
+ # /// script
+ # requires-python = ">=3.11"
+ # dependencies = ["polars"]
+ # ///
+
+ import marimo
+ app = marimo.App()
+
+ @app.cell
+ def __():
+ import marimo as mo
+ return mo,
+
+ @app.cell
+ def __(mo):
+ slider = mo.ui.slider(0, 10)
+ return slider,
+
+ if __name__ == "__main__":
+ app.run()
+ """
+ )
+
+ try:
+ with open(tmp_file, "w") as f:
+ f.write(content)
+ yield tmp_file
+ finally:
+ tmp_dir.cleanup()
+
+
def test_cli_help_exit_code() -> None:
# smoke test: makes sure CLI starts
# helpful for catching issues related to
@@ -535,6 +573,41 @@ def test_cli_sandbox_run(temp_marimo_file: str) -> None:
_check_contents(p, b"marimo-mode data-mode='read'", contents)
[email protected](not HAS_UV, reason="uv is required for sandbox tests")
+def test_cli_sandbox_run_with_python_version(
+ temp_marimo_file_with_inline_metadata: str,
+) -> None:
+ port = _get_port()
+ p = subprocess.Popen(
+ [
+ "marimo",
+ "run",
+ temp_marimo_file_with_inline_metadata,
+ "-p",
+ str(port),
+ "--headless",
+ "--sandbox",
+ ],
+ stderr=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ text=True,
+ )
+
+ contents = _try_fetch(port)
+
+ # If fetch fails, capture and print server output for debugging
+ if contents is None:
+ stdout, stderr = p.communicate(timeout=5)
+ raise AssertionError(
+ f"Server failed to start. stdout:\n{stdout}\nstderr:\n{stderr}"
+ )
+
+ _check_contents(p, b"marimo-mode data-mode='read'", contents)
+
+ p.terminate()
+ p.wait(timeout=5)
+
+
@pytest.mark.xfail(condition=_is_win32(), reason="flaky on Windows")
def test_cli_edit_interrupt_twice() -> None:
# two SIGINTs should kill the CLI
diff --git a/tests/_cli/test_sandbox.py b/tests/_cli/test_sandbox.py
index 7a3d386d45..795cdfbec8 100644
--- a/tests/_cli/test_sandbox.py
+++ b/tests/_cli/test_sandbox.py
@@ -4,7 +4,9 @@ import pytest
from marimo._cli.sandbox import (
_get_dependencies,
+ _get_python_version_requirement,
_pyproject_toml_to_requirements_txt,
+ _read_pyproject,
)
@@ -179,3 +181,44 @@ def test_pyproject_toml_to_requirements_txt_with_versioned_dependencies(
assert _pyproject_toml_to_requirements_txt(pyproject) == [
"marimo @ git+https://github.com/marimo-team/marimo.git@main",
]
+
+
+def test_get_python_version_requirement():
+ pyproject = {"requires-python": ">=3.11"}
+ assert _get_python_version_requirement(pyproject) == ">=3.11"
+
+ pyproject = {"dependencies": ["polars"]}
+ assert _get_python_version_requirement(pyproject) is None
+
+ assert _get_python_version_requirement(None) is None
+
+ pyproject = {"requires-python": {"invalid": "type"}}
+ assert _get_python_version_requirement(pyproject) is None
+
+
+def test_get_dependencies_with_python_version():
+ SCRIPT = """
+# /// script
+# requires-python = ">=3.11"
+# dependencies = ["polars"]
+# ///
+
+import marimo
+"""
+ assert _get_dependencies(SCRIPT) == ["polars"]
+
+ pyproject = _read_pyproject(SCRIPT)
+ assert pyproject is not None
+ assert _get_python_version_requirement(pyproject) == ">=3.11"
+
+ SCRIPT_NO_PYTHON = """
+# /// script
+# dependencies = ["polars"]
+# ///
+
+import marimo
+"""
+ pyproject_no_python = _read_pyproject(SCRIPT_NO_PYTHON)
+ assert pyproject_no_python is not None
+ assert _get_python_version_requirement(pyproject_no_python) is None
+ assert _get_dependencies(SCRIPT_NO_PYTHON) == ["polars"]