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.

improvements for running as a script (#973)

Akshay Agrawald3c9db248a57
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index 59ab8191a0..8f8247f913 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -246,6 +246,15 @@ class App:
)
def run(self) -> tuple[Sequence[Any], dict[str, Any]]:
+ # formatters aren't automatically registered when running as a script
+ from marimo._output.formatters.formatters import (
+ register_formatters,
+ )
+ from marimo._output.formatting import FORMATTERS
+
+ if not FORMATTERS:
+ register_formatters()
+
return asyncio.run(self._run_async())
async def _run_cell_async(
diff --git a/marimo/_output/hypertext.py b/marimo/_output/hypertext.py
index c726dd567d..02a38252e8 100644
--- a/marimo/_output/hypertext.py
+++ b/marimo/_output/hypertext.py
@@ -7,6 +7,7 @@ from marimo._messaging.mimetypes import KnownMimeType
from marimo._output.mime import MIME
from marimo._output.rich_help import mddoc
from marimo._output.utils import flatten_string
+from marimo._utils.exiting import python_exiting
if TYPE_CHECKING:
from marimo._plugins.core.web_component import JSONType
@@ -91,6 +92,10 @@ class Html(MIME):
Subclasses MUST implement a __del__ method that ends by calling
this method.
"""
+ if python_exiting():
+ # imports can fail when python is exiting; clean-up
+ # is not important when exiting anyway
+ return
from marimo._runtime.context import (
ContextNotInitializedError,
@@ -102,8 +107,9 @@ class Html(MIME):
except ContextNotInitializedError:
return
- for f in self._virtual_filenames:
- ctx.virtual_file_registry.dereference(f)
+ if ctx is not None:
+ for f in self._virtual_filenames:
+ ctx.virtual_file_registry.dereference(f)
@property
def text(self) -> str:
diff --git a/marimo/_utils/exiting.py b/marimo/_utils/exiting.py
new file mode 100644
index 0000000000..77c141b194
--- /dev/null
+++ b/marimo/_utils/exiting.py
@@ -0,0 +1,22 @@
+# Copyright 2024 Marimo. All rights reserved.
+import atexit
+from dataclasses import dataclass
+
+
+@dataclass
+class Exiting:
+ value: bool = False
+
+
+_PYTHON_EXITING = Exiting()
+
+
+def python_exiting() -> bool:
+ return _PYTHON_EXITING.value
+
+
+def _exit() -> None:
+ _PYTHON_EXITING.value = True
+
+
+atexit.register(_exit)