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: `marimo export script`, to export notebook as a flat script (#1199)
Myles Scolnicke651560eb34d
diff --git a/docs/guides/editor_features.md b/docs/guides/editor_features.mdindex 1d0ee616e9..35dba8ad79 100644--- a/docs/guides/editor_features.md+++ b/docs/guides/editor_features.md@@ -22,7 +22,6 @@ To access these settings, click the gear icon in the top-right of the editor.</figure></div>-## Overview panelsmarimo ships with the following IDE-like panels that help provide an overview@@ -121,7 +120,6 @@ You can also export to HTML at the command-line:marimo export html notebook.py -o notebook.html```-## ConfigurationClick the settings icon in the top right to access important configurationdiff --git a/docs/guides/exporting.md b/docs/guides/exporting.mdnew file mode 100644index 0000000000..364e91ae42--- /dev/null+++ b/docs/guides/exporting.md@@ -0,0 +1,41 @@+# Exporting++## Export to static HTML++Export the current view your notebook to static HTML via the notebook+menu:++<div align="center">+<figure>+<img src="/_static/docs-html-export.png"/>+<figcaption>Download as static HTML.</figcaption>+</figure>+</div>++You can also export to HTML at the command-line:++```bash+marimo export html notebook.py -o notebook.html+```++or watch the notebook for changes and automatically export to HTML:++```bash+marimo export html notebook.py -o notebook.html --watch+```++## Export to a Python script++Export the notebook to a flat Python script at the command-line.+This exports the notebook in topological order, so the cells adhere to their dependency graph.++```bash+marimo export script notebook.py -o notebook.script.py+```++```{admonition} Top-level await not supported+:class: warning++Exporting to a flat Python script does not support top-level await.+If you have top-level await in your notebook, you can still execute the notebook as a script with `python notebook.py`.+```diff --git a/docs/guides/index.md b/docs/guides/index.mdindex e9ba3b5645..d13b6eb0fb 100644--- a/docs/guides/index.md+++ b/docs/guides/index.md@@ -21,6 +21,7 @@ai_completionbest_practicesperformance+ exportingdeploying/index```@@ -44,6 +45,7 @@ These guides cover marimo's core concepts.| {doc}`performance` | Writing performant notebooks || {doc}`wasm` | Running notebooks in the browser (no backend required!) || {doc}`ai_completion` | Using AI to speed up your coding |+| {doc}`exporting` | Exporting notebooks to HTML and flat scripts || {doc}`deploying/index` | Deploying marimo notebooks and apps |```{admonition} Learn by doing!diff --git a/marimo/_cli/export/commands.py b/marimo/_cli/export/commands.pyindex 5efbaf1588..3be3869a85 100644--- a/marimo/_cli/export/commands.py+++ b/marimo/_cli/export/commands.py@@ -8,7 +8,10 @@ import clickfrom marimo._cli.parse_args import parse_argsfrom marimo._cli.print import green-from marimo._server.export.utils import run_app_then_export_as_html+from marimo._server.export.utils import (+ export_as_script,+ run_app_then_export_as_html,+)from marimo._utils.file_watcher import FileWatcherfrom marimo._utils.paths import maybe_make_dirs@@ -123,4 +126,94 @@ def html(asyncio.run(start())+ help="""+Export a marimo notebook as a flat script, in topological order.++Example:++ \b+ * marimo export script notebook.py -o notebook.script.py++Watch for changes and regenerate the script on modification:++ \b+ * marimo export script notebook.py -o notebook.script.py --watch+"""+)+ "--watch/--no-watch",+ default=False,+ show_default=True,+ type=bool,+ help="""+ Watch notebook for changes and regenerate the script on modification.+ If watchdog is installed, it will be used to watch the file.+ Otherwise, file watcher will poll the file every 1s.+ """,+)+ "-o",+ "--output",+ type=str,+ default=None,+ help="""+ Output file to save the script to.+ If not provided, the script will be printed to stdout.+ """,+)[email protected]("name", required=True)+def script(+ name: str,+ output: str,+ watch: bool,+) -> None:+ """+ Export a marimo notebook as a flat script, in topological order.+ """+ if watch and not output:+ raise click.UsageError(+ "Cannot use --watch without providing "+ + "an output file with --output."+ )++ def write_script(script: str) -> None:+ if output:+ # Make dirs if needed+ maybe_make_dirs(output)+ with open(output, "w") as f:+ f.write(script)+ f.close()+ else:+ click.echo(script)++ # No watch, just run once+ if not watch:+ (html, _filename) = export_as_script(name)+ write_script(html)+ return++ async def on_file_changed(file_path: Path) -> None:+ click.echo(+ f"File {str(file_path)} changed. Re-exporting to {green(output)}"+ )+ (script, _filename) = export_as_script(str(file_path))+ write_script(script)++ async def start() -> None:+ # Watch the file for changes+ watcher = FileWatcher.create(Path(name), on_file_changed)+ click.echo(f"Watching {green(name)} for changes...")+ watcher.start()+ try:+ # Run forever+ while True:+ await asyncio.sleep(1)+ except KeyboardInterrupt:+ watcher.stop()++ asyncio.run(start())++export.add_command(html)+export.add_command(script)diff --git a/marimo/_server/api/endpoints/export.py b/marimo/_server/api/endpoints/export.pyindex d348481a3d..625b55b49e 100644--- a/marimo/_server/api/endpoints/export.py+++ b/marimo/_server/api/endpoints/export.py@@ -4,13 +4,16 @@ from __future__ import annotationsfrom typing import TYPE_CHECKINGfrom starlette.authentication import requires-from starlette.responses import HTMLResponse+from starlette.responses import HTMLResponse, PlainTextResponsefrom marimo import _loggersfrom marimo._server.api.deps import AppStatefrom marimo._server.api.utils import parse_requestfrom marimo._server.export.exporter import Exporter-from marimo._server.models.export import ExportAsHTMLRequest+from marimo._server.models.export import (+ ExportAsHTMLRequest,+ ExportAsScriptRequest,+)from marimo._server.router import APIRouterif TYPE_CHECKING:@@ -54,3 +57,32 @@ async def export_as_html(content=html,headers=headers,)++[email protected]("/script")+@requires("edit")+async def export_as_script(+ *,+ request: Request,+) -> PlainTextResponse:+ """+ Export the notebook as a script.+ """+ app_state = AppState(request)+ body = await parse_request(request, cls=ExportAsScriptRequest)+ session = app_state.require_current_session()++ python, filename = Exporter().export_as_script(+ file_manager=session.app_file_manager,+ )++ if body.download:+ headers = {"Content-Disposition": f"attachment; filename={filename}"}+ else:+ headers = {}++ # Download the Script+ return PlainTextResponse(+ content=python,+ headers=headers,+ )diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.pyindex 532b8c8bc4..5f47239703 100644--- a/marimo/_server/export/exporter.py+++ b/marimo/_server/export/exporter.py@@ -5,6 +5,9 @@ import mimetypesimport osfrom typing import cast+from click import UsageError++from marimo import __version__from marimo._config.config import (DEFAULT_CONFIG,DisplayConfig,@@ -12,6 +15,7 @@ from marimo._config.config import ()from marimo._messaging.mimetypes import KnownMimeTypefrom marimo._output.utils import build_data_url+from marimo._runtime import dataflowfrom marimo._runtime.virtual_file import read_virtual_filefrom marimo._server.file_manager import AppFileManagerfrom marimo._server.models.export import ExportAsHTMLRequest@@ -88,3 +92,35 @@ class Exporter:download_filename = f"{os.path.splitext(basename)[0]}.html"return html, download_filename++ def export_as_script(+ self,+ file_manager: AppFileManager,+ ) -> tuple[str, str]:+ # Check if any code is async, if so, raise an error+ for cell in file_manager.app.cell_manager.cells():+ if not cell:+ continue+ if cell._is_coroutine():+ raise UsageError(+ "Cannot export a notebook with async code to a flat script"+ )++ graph = file_manager.app.graph+ codes: list[str] = [+ graph.cells[cid].code+ for cid in dataflow.topological_sort(graph, graph.cells.keys())+ ]+ filename = file_manager.filename+ if not filename:+ filename = "notebook.script.py"++ basename = os.path.basename(filename)+ download_filename = f"{os.path.splitext(basename)[0]}.script.py"++ code = (+ f'\n__generated_with = "{__version__}"\n\n'+ + "\n\n# ---\n\n".join(codes)+ )++ return code, download_filenamediff --git a/marimo/_server/export/utils.py b/marimo/_server/export/utils.pyindex c2d0c5a8dc..67a12a06bc 100644--- a/marimo/_server/export/utils.py+++ b/marimo/_server/export/utils.py@@ -17,6 +17,17 @@ from marimo._server.models.models import InstantiateRequestfrom marimo._server.sessions import Session+def export_as_script(+ filename: str,+) -> tuple[str, str]:+ file_router = AppFileRouter.from_filename(filename)+ file_key = file_router.get_unique_file_key()+ assert file_key is not None+ file_manager = file_router.get_file_manager(file_key)++ return Exporter().export_as_script(file_manager)++async def run_app_then_export_as_html(filename: str,include_code: bool,diff --git a/marimo/_server/models/export.py b/marimo/_server/models/export.pyindex a6dd360342..54cc7fa044 100644--- a/marimo/_server/models/export.py+++ b/marimo/_server/models/export.py@@ -11,3 +11,8 @@ class ExportAsHTMLRequest:files: List[str]include_code: boolasset_url: Optional[str] = None+++@dataclass+class ExportAsScriptRequest:+ download: booldiff --git a/marimo/_server/router.py b/marimo/_server/router.pyindex caf753ec8e..cd4ea7dc5d 100644--- a/marimo/_server/router.py+++ b/marimo/_server/router.py@@ -11,6 +11,7 @@ from starlette.responses import (FileResponse,HTMLResponse,JSONResponse,+ PlainTextResponse,Response,StreamingResponse,)@@ -56,6 +57,8 @@ class APIRouter(Router):return responseif isinstance(response, HTMLResponse):return response+ if isinstance(response, PlainTextResponse):+ return responseif dataclasses.is_dataclass(response):return JSONResponse(diff --git a/tests/_cli/snapshots/script.txt b/tests/_cli/snapshots/script.txtnew file mode 100644index 0000000000..72e63c6357--- /dev/null+++ b/tests/_cli/snapshots/script.txt@@ -0,0 +1,8 @@++__generated_with = "0.4.2"++import marimo as mo++# ---++slider = mo.ui.slider(0, 10)diff --git a/tests/_cli/test_cli_export.py b/tests/_cli/test_cli_export.pyindex cd23a8c7b1..e02b8297b9 100644--- a/tests/_cli/test_cli_export.py+++ b/tests/_cli/test_cli_export.py@@ -1,6 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+import asyncioimport subprocessfrom os import path@@ -10,105 +11,202 @@ from tests.mocks import snapshottersnapshot = snapshotter(__file__)-def test_cli_export_html(temp_marimo_file: str) -> None:- p = subprocess.run(- ["marimo", "export", "html", temp_marimo_file],- capture_output=True,- )- assert p.returncode == 0, p.stderr.decode()- html = normalize_index_html(p.stdout.decode())- # Remove folder path- dirname = path.dirname(temp_marimo_file)- html = html.replace(dirname, "path")- assert '<marimo-code hidden=""></marimo-code>' not in html---def test_cli_export_html_no_code(temp_marimo_file: str) -> None:- p = subprocess.run(- ["marimo", "export", "html", temp_marimo_file, "--no-include-code"],- capture_output=True,- )- assert p.returncode == 0, p.stderr.decode()- html = normalize_index_html(p.stdout.decode())- # Remove folder path- dirname = path.dirname(temp_marimo_file)- html = html.replace(dirname, "path")- assert '<marimo-code hidden=""></marimo-code>' in html---def test_cli_export_async(temp_async_marimo_file: str) -> None:- p = subprocess.run(- ["marimo", "export", "html", temp_async_marimo_file],- capture_output=True,- )- assert p.returncode == 0, p.stderr.decode()- assert "ValueError" not in p.stderr.decode()- assert "Traceback" not in p.stderr.decode()- html = normalize_index_html(p.stdout.decode())- # Remove folder path- dirname = path.dirname(temp_async_marimo_file)- html = html.replace(dirname, "path")- assert '<marimo-code hidden=""></marimo-code>' not in html---async def test_export_watch(temp_marimo_file: str) -> None:- temp_out_file = temp_marimo_file.replace(".py", ".html")- p = subprocess.Popen( # noqa: ASYNC101- [- "marimo",- "export",- "html",- temp_marimo_file,- "--watch",- "--output",- temp_out_file,- ],- stdout=subprocess.PIPE,- stderr=subprocess.PIPE,- )-- # Wait for the message- while True:- line = p.stdout.readline().decode()- if line:- assert f"Watching {temp_marimo_file}" in line- break-- assert not path.exists(temp_out_file)-- # Modify file- with open(temp_marimo_file, "a") as f: # noqa: ASYNC101- f.write("\n# comment\n")-- assert p.poll() is None- # Wait for rebuild- while True:- line = p.stdout.readline().decode()- if line:- assert "Re-exporting" in line- break---def test_export_watch_no_out_dir(temp_marimo_file: str) -> None:- p = subprocess.Popen(- [- "marimo",- "export",- "html",- temp_marimo_file,- "--watch",- ],- stdout=subprocess.PIPE,- stderr=subprocess.PIPE,- )-- # Should return an error- while True:- line = p.stderr.readline().decode()- if line:- assert (- "Cannot use --watch without providing "- + "an output file with --output."- in line- )- break+class TestExportHTML:+ @staticmethod+ def test_cli_export_html(temp_marimo_file: str) -> None:+ p = subprocess.run(+ ["marimo", "export", "html", temp_marimo_file],+ capture_output=True,+ )+ assert p.returncode == 0, p.stderr.decode()+ html = normalize_index_html(p.stdout.decode())+ # Remove folder path+ dirname = path.dirname(temp_marimo_file)+ html = html.replace(dirname, "path")+ assert '<marimo-code hidden=""></marimo-code>' not in html++ @staticmethod+ def test_cli_export_html_no_code(temp_marimo_file: str) -> None:+ p = subprocess.run(+ [+ "marimo",+ "export",+ "html",+ temp_marimo_file,+ "--no-include-code",+ ],+ capture_output=True,+ )+ assert p.returncode == 0, p.stderr.decode()+ html = normalize_index_html(p.stdout.decode())+ # Remove folder path+ dirname = path.dirname(temp_marimo_file)+ html = html.replace(dirname, "path")+ assert '<marimo-code hidden=""></marimo-code>' in html++ @staticmethod+ def test_cli_export_async(temp_async_marimo_file: str) -> None:+ p = subprocess.run(+ ["marimo", "export", "html", temp_async_marimo_file],+ capture_output=True,+ )+ assert p.returncode == 0, p.stderr.decode()+ assert "ValueError" not in p.stderr.decode()+ assert "Traceback" not in p.stderr.decode()+ html = normalize_index_html(p.stdout.decode())+ # Remove folder path+ dirname = path.dirname(temp_async_marimo_file)+ html = html.replace(dirname, "path")+ assert '<marimo-code hidden=""></marimo-code>' not in html++ @staticmethod+ async def test_export_watch(temp_marimo_file: str) -> None:+ temp_out_file = temp_marimo_file.replace(".py", ".html")+ p = subprocess.Popen( # noqa: ASYNC101+ [+ "marimo",+ "export",+ "html",+ temp_marimo_file,+ "--watch",+ "--output",+ temp_out_file,+ ],+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ )++ # Wait for the message+ while True:+ line = p.stdout.readline().decode()+ if line:+ assert f"Watching {temp_marimo_file}" in line+ break++ assert not path.exists(temp_out_file)++ # Modify file+ with open(temp_marimo_file, "a") as f: # noqa: ASYNC101+ f.write("\n# comment\n")++ assert p.poll() is None+ # Wait for rebuild+ while True:+ line = p.stdout.readline().decode()+ if line:+ assert "Re-exporting" in line+ break++ @staticmethod+ def test_export_watch_no_out_dir(temp_marimo_file: str) -> None:+ p = subprocess.Popen(+ [+ "marimo",+ "export",+ "html",+ temp_marimo_file,+ "--watch",+ ],+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ )++ # Should return an error+ while True:+ line = p.stderr.readline().decode()+ if line:+ assert (+ "Cannot use --watch without providing "+ + "an output file with --output."+ in line+ )+ break+++class TestExportScript:+ @staticmethod+ def test_export_script(temp_marimo_file: str) -> None:+ p = subprocess.run(+ ["marimo", "export", "script", temp_marimo_file],+ capture_output=True,+ )+ assert p.returncode == 0, p.stderr.decode()+ snapshot("script.txt", p.stdout.decode())++ @staticmethod+ def test_export_script_async(temp_async_marimo_file: str) -> None:+ p = subprocess.run(+ ["marimo", "export", "script", temp_async_marimo_file],+ capture_output=True,+ )+ assert p.returncode == 2, p.stderr.decode()+ assert (+ "Cannot export a notebook with async code to a flat script"+ in p.stderr.decode()+ )++ @staticmethod+ async def test_export_watch_script(temp_marimo_file: str) -> None:+ temp_out_file = temp_marimo_file.replace(".py", ".script.py")+ p = subprocess.Popen( # noqa: ASYNC101+ [+ "marimo",+ "export",+ "script",+ temp_marimo_file,+ "--watch",+ "--output",+ temp_out_file,+ ],+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ )++ # Wait for the message+ while True:+ line = p.stdout.readline().decode()+ if line:+ assert f"Watching {temp_marimo_file}" in line+ break++ assert not path.exists(temp_out_file)++ # Modify file+ with open(temp_marimo_file, "a") as f: # noqa: ASYNC101+ f.write("\n# comment\n")++ assert p.poll() is None+ # Wait for rebuild+ while True:+ line = p.stdout.readline().decode()+ if line:+ assert "Re-exporting" in line+ break++ await asyncio.sleep(0.1)+ assert path.exists(temp_out_file)++ @staticmethod+ def test_export_watch_script_no_out_dir(temp_marimo_file: str) -> None:+ p = subprocess.Popen(+ [+ "marimo",+ "export",+ "script",+ temp_marimo_file,+ "--watch",+ ],+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ )++ # Should return an error+ while True:+ line = p.stderr.readline().decode()+ if line:+ assert (+ "Cannot use --watch without providing "+ + "an output file with --output."+ in line+ )+ breakdiff --git a/tests/_server/api/endpoints/test_export.py b/tests/_server/api/endpoints/test_export.pyindex da687ff84f..3a38776002 100644--- a/tests/_server/api/endpoints/test_export.py+++ b/tests/_server/api/endpoints/test_export.py@@ -53,3 +53,16 @@ def test_export_html_no_code(client: TestClient) -> None:)body = response.textassert '<marimo-code hidden=""></marimo-code>' in body+++@with_session(SESSION_ID)+def test_export_script(client: TestClient) -> None:+ response = client.post(+ "/api/export/script",+ headers=HEADERS,+ json={+ "download": False,+ },+ )+ assert response.status_code == 200+ assert "__generated_with = " in response.textdiff --git a/tests/conftest.py b/tests/conftest.pyindex 8700e38639..79e1f723a6 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -156,6 +156,11 @@ def temp_marimo_file() -> Generator[str, None, None]:import marimo as moreturn mo,+ @app.cell+ def __(mo):+ slider = mo.ui.slider(0, 10)+ return slider,+if __name__ == "__main__":app.run()"""