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
fix: set event loop policy before HTML export (#1252)
Akshay Agrawal6d753e2fa11a
diff --git a/.github/workflows/test_cli.yaml b/.github/workflows/test_cli.yamlindex 06e7fb13bf..f7d5021bde 100644--- a/.github/workflows/test_cli.yaml+++ b/.github/workflows/test_cli.yaml@@ -109,4 +109,4 @@ jobs:- name: Test CLIshell: bash- run: pytest -v tests/_cli/test_cli.py+ run: pytest -v tests/_cli/test_cli.py tests/_cli/test_cli_export.pydiff --git a/marimo/_cli/export/commands.py b/marimo/_cli/export/commands.pyindex 3be3869a85..4372b737fb 100644--- a/marimo/_cli/export/commands.py+++ b/marimo/_cli/export/commands.py@@ -12,6 +12,7 @@ from marimo._server.export.utils import (export_as_script,run_app_then_export_as_html,)+from marimo._server.utils import asyncio_runfrom marimo._utils.file_watcher import FileWatcherfrom marimo._utils.paths import maybe_make_dirs@@ -94,7 +95,7 @@ def html(cli_args = parse_args(args)# No watch, just run onceif not watch:- (html, _filename) = asyncio.run(+ (html, _filename) = asyncio_run(run_app_then_export_as_html(name, include_code=include_code, cli_args=cli_args)@@ -123,7 +124,7 @@ def html(except KeyboardInterrupt:watcher.stop()- asyncio.run(start())+ asyncio_run(start())@click.command(@@ -212,7 +213,7 @@ def script(except KeyboardInterrupt:watcher.stop()- asyncio.run(start())+ asyncio_run(start())export.add_command(html)diff --git a/marimo/_server/export/utils.py b/marimo/_server/export/utils.pyindex 96c6c489d4..26df1d05b8 100644--- a/marimo/_server/export/utils.py+++ b/marimo/_server/export/utils.py@@ -2,7 +2,6 @@from __future__ import annotationsimport asyncio-from multiprocessing import Processfrom typing import Callablefrom marimo._config.manager import UserConfigManager@@ -117,10 +116,7 @@ async def run_app_until_completion(# Hack: yield to give the session view a chance to process the incoming# console operations.await asyncio.sleep(0.1)-- # Terminate the running kernel task -- all information is captured by- # the session view.- kernel_task = session.kernel_manager.kernel_task- if kernel_task is not None and isinstance(kernel_task, Process):- kernel_task.terminate()+ # Stop distributor, terminate kernel process, etc -- all information is+ # captured by the session view.+ session.close()return sessiondiff --git a/marimo/_server/start.py b/marimo/_server/start.pyindex 9677b74960..3a168b1382 100644--- a/marimo/_server/start.py+++ b/marimo/_server/start.py@@ -12,14 +12,8 @@ from marimo._runtime.requests import SerializedCLIArgsfrom marimo._server.file_router import AppFileRouterfrom marimo._server.main import create_starlette_appfrom marimo._server.model import SessionMode-from marimo._server.sessions import (- LspServer,- SessionManager,-)-from marimo._server.utils import (- find_free_port,- initialize_asyncio,-)+from marimo._server.sessions import LspServer, SessionManager+from marimo._server.utils import find_free_port, initialize_asynciofrom marimo._server.uvicorn_utils import initialize_signalsfrom marimo._utils.paths import import_filesdiff --git a/marimo/_server/utils.py b/marimo/_server/utils.pyindex 07ef85e4ee..fafd6e7af7 100644--- a/marimo/_server/utils.py+++ b/marimo/_server/utils.py@@ -1,11 +1,17 @@# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations+import asyncioimport osimport pathlibimport sys+from typing import TYPE_CHECKING, Any, TypeVarfrom marimo import _loggers+if TYPE_CHECKING:+ from collections.abc import Coroutine+# use spaces instead of a tab to play well with carriage returns;# \r\t doesn't appear to overwrite characters at the start of a line,# but \r{TAB} does ...@@ -54,6 +60,26 @@ def initialize_mimetypes() -> None:def initialize_asyncio() -> None:- """Platform-specific initialization of asyncio."""+ """Platform-specific initialization of asyncio.++ Sessions use the `add_reader()` API, which is only available in the+ SelectorEventLoop policy; Windows uses the Proactor by default.+ """if sys.platform == "win32":asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())+++T = TypeVar("T")+++def asyncio_run(coro: Coroutine[Any, Any, T], **kwargs: dict[Any, Any]) -> T:+ """asyncio.run() with platform-specific initialization.++ When using Sessions, make sure to use this method instead of `asyncio.run`.++ If not using a Session, don't call this method.++ `kwargs` are passed to `asyncio.run()`+ """+ initialize_asyncio()+ return asyncio.run(coro, **kwargs) # type: ignore[arg-type]diff --git a/marimo/_utils/distributor.py b/marimo/_utils/distributor.pyindex 6cb4af8f40..9241a4e892 100644--- a/marimo/_utils/distributor.py+++ b/marimo/_utils/distributor.py@@ -22,6 +22,14 @@ class Distributor(Generic[T]):consumers.This also handles adding and removing new consumers.++ NOTE: This class uses the `add_reader()` API, which requires the+ SelectorEventLoop to be used on Windows, not the default ProactorEventLoop.+ See++ https://bugs.python.org/issue37373#:~:text=On%20Windows%20there%20are%20two,subprocesses%20and%20generally%20lower%20scalability.++ for context."""def __init__(self, input_connection: TypedConnection[T]) -> None:diff --git a/tests/_cli/test_cli_export.py b/tests/_cli/test_cli_export.pyindex 9fe5cd7b27..68fde5775a 100644--- a/tests/_cli/test_cli_export.py+++ b/tests/_cli/test_cli_export.py@@ -10,6 +10,7 @@ from typing import TYPE_CHECKINGimport pytestfrom marimo import __version__+from marimo._dependencies.dependencies import DependencyManagerfrom tests._server.templates.utils import normalize_index_htmlfrom tests.mocks import snapshotter@@ -67,8 +68,11 @@ class TestExportHTML: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:+ @pytest.mark.skipif(+ condition=DependencyManager.has_watchdog(),+ reason="hangs when watchdog is installed",+ )+ async def test_export_watch(self, temp_marimo_file: str) -> None:temp_out_file = temp_marimo_file.replace(".py", ".html")p = subprocess.Popen( # noqa: ASYNC101[@@ -99,14 +103,18 @@ class TestExportHTML:assert p.poll() is None# Wait for rebuild+ # TODO: This hangs when watchdog is installed.while True:line = p.stdout.readline().decode()if line:assert "Re-exporting" in linebreak- @staticmethod- def test_export_watch_no_out_dir(temp_marimo_file: str) -> None:+ @pytest.mark.skipif(+ condition=DependencyManager.has_watchdog(),+ reason="hangs when watchdog is installed",+ )+ def test_export_watch_no_out_dir(self, temp_marimo_file: str) -> None:p = subprocess.Popen(["marimo",@@ -150,7 +158,7 @@ class TestExportHtmlSmokeTests:file = tmp_path / "intro.py"out = tmp_path / "out.html"- file.write_text(inspect.getsource(intro))+ file.write_text(inspect.getsource(intro), encoding="utf-8")p = subprocess.run(["marimo", "export", "html", str(file), "-o", str(out)],capture_output=True,@@ -161,7 +169,7 @@ class TestExportHtmlSmokeTests:from marimo._tutorials import ui as modfile = tmp_path / "mod.py"- file.write_text(inspect.getsource(mod))+ file.write_text(inspect.getsource(mod), encoding="utf-8")out = tmp_path / "out.html"p = subprocess.run(["marimo", "export", "html", str(file), "-o", str(out)],@@ -169,14 +177,11 @@ class TestExportHtmlSmokeTests:)self.assert_not_errored(p)- @pytest.mark.xfail(- condition=True, reason="export HTML not yet capturing console outputs"- )def test_export_dataflow_tutorial(self, tmp_path: pathlib.Path) -> None:from marimo._tutorials import dataflow as modfile = tmp_path / "mod.py"- file.write_text(inspect.getsource(mod))+ file.write_text(inspect.getsource(mod), encoding="utf-8")out = tmp_path / "out.html"p = subprocess.run(["marimo", "export", "html", str(file), "-o", str(out)],@@ -188,7 +193,7 @@ class TestExportHtmlSmokeTests:from marimo._tutorials import layout as modfile = tmp_path / "mod.py"- file.write_text(inspect.getsource(mod))+ file.write_text(inspect.getsource(mod), encoding="utf-8")out = tmp_path / "out.html"p = subprocess.run(["marimo", "export", "html", str(file), "-o", str(out)],@@ -197,10 +202,10 @@ class TestExportHtmlSmokeTests:self.assert_not_errored(p)def test_export_plots_tutorial(self, tmp_path: pathlib.Path) -> None:- from marimo._tutorials import plots+ from marimo._tutorials import plots as modfile = tmp_path / "plots.py"- file.write_text(inspect.getsource(plots))+ file.write_text(inspect.getsource(mod), encoding="utf-8")out = tmp_path / "out.html"p = subprocess.run(["marimo", "export", "html", str(file), "-o", str(out)],@@ -208,16 +213,13 @@ class TestExportHtmlSmokeTests:)self.assert_not_errored(p)- @pytest.mark.xfail(- condition=True, reason="export HTML not yet capturing console outputs"- )def test_export_marimo_for_jupyter_users(self, tmp_path: pathlib.Path) -> None:from marimo._tutorials import marimo_for_jupyter_users as modfile = tmp_path / "mod.py"- file.write_text(inspect.getsource(mod))+ file.write_text(inspect.getsource(mod), encoding="utf-8")out = tmp_path / "out.html"p = subprocess.run(["marimo", "export", "html", str(file), "-o", str(out)],@@ -250,8 +252,11 @@ class TestExportScript:in p.stderr.decode())- @staticmethod- async def test_export_watch_script(temp_marimo_file: str) -> None:+ @pytest.mark.skipif(+ condition=DependencyManager.has_watchdog(),+ reason="hangs when watchdog is installed",+ )+ async def test_export_watch_script(self, temp_marimo_file: str) -> None:temp_out_file = temp_marimo_file.replace(".py", ".script.py")p = subprocess.Popen( # noqa: ASYNC101[@@ -291,8 +296,13 @@ class TestExportScript: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:+ @pytest.mark.skipif(+ condition=DependencyManager.has_watchdog(),+ reason="hangs when watchdog is installed",+ )+ def test_export_watch_script_no_out_dir(+ self, temp_marimo_file: str+ ) -> None:p = subprocess.Popen(["marimo",diff --git a/tests/mocks.py b/tests/mocks.pyindex c02c78dc58..110bc5e6e8 100644--- a/tests/mocks.py+++ b/tests/mocks.py@@ -26,6 +26,11 @@ def snapshotter(current_file: str) -> Callable[[str, str], None]:# If snapshot directory doesn't exist, create itmaybe_make_dirs(filepath)+ def normalize(string: str) -> str:+ return string.replace("\r\n", "\n")++ result = normalize(result)+# If doesn't exist, create snapshotif not os.path.exists(filepath):with open(filepath, "w") as f:@@ -34,13 +39,14 @@ def snapshotter(current_file: str) -> Callable[[str, str], None]:# Read snapshotwith open(filepath, "r") as f:- expected = f.read()+ expected = normalize(f.read())with open(filepath, "w") as f:f.write(result)assert result, "Result is empty"assert expected, "Expected is empty"+text_diff = "\n".join(list(difflib.unified_diff(@@ -50,8 +56,7 @@ def snapshotter(current_file: str) -> Callable[[str, str], None]:)))- if expected != result:- print(f"Snapshot differs:\n{text_diff}")- assert result == expected++ assert result == expected, f"Snapshot differs:\n{text_diff}"return snapshot