from __future__ import annotations
import os
import sys
from contextlib import contextmanager
from subprocess import PIPE, Popen # ruff:ignore[suspicious-subprocess-import] # the backend is spawned with a fixed argv, no shell
from threading import Thread
from typing import TYPE_CHECKING, Any, Final, cast
from ._frontend import CmdStatus, Frontend
if TYPE_CHECKING:
from collections.abc import Generator
from pathlib import Path
from packaging.requirements import Requirement
[docs]
class SubprocessFrontend(Frontend):
"""
A frontend that creates fresh subprocess at every call to communicate with the backend.
:ivar executable: the interpreter that runs the backend in a subprocess
"""
def __init__(
self,
root: Path,
backend_paths: tuple[Path, ...],
backend_module: str,
backend_obj: str | None,
requires: tuple[Requirement, ...],
) -> None:
"""
Create a subprocess frontend.
:param root: the root path to the built project
:param backend_paths: paths that are available on the python path for the backend
:param backend_module: module where the backend is located
:param backend_obj: object within the backend module identifying the backend
:param requires: seed requirements for the backend
"""
super().__init__(root, backend_paths, backend_module, backend_obj, requires, reuse_backend=False)
self.executable = sys.executable
@contextmanager
def _send_msg(self, cmd: str, result_file: Path, msg: str) -> Generator[SubprocessCmdStatus, None, None]: # ruff:ignore[unused-method-argument] # mirrors the Frontend._send_msg signature
env = os.environ.copy()
if backend := os.pathsep.join(str(i) for i in self._backend_paths):
# backend-path goes first (PEP 517), but what the caller already put on PYTHONPATH must stay importable
env["PYTHONPATH"] = os.pathsep.join(filter(None, (backend, env.get("PYTHONPATH"))))
process = Popen( # ruff:ignore[subprocess-without-shell-equals-true] # fixed argv, no shell
args=[self.executable, *self.backend_args],
stdout=PIPE,
stderr=PIPE,
stdin=PIPE,
universal_newlines=True,
errors="backslashreplace",
cwd=self._root,
env=env,
)
status: Final = SubprocessCmdStatus(process, f"{os.linesep}{msg}{os.linesep}")
try:
yield status
finally:
process.kill()
status.join()
[docs]
def send_cmd(
self,
cmd: str,
**kwargs: Any, # simplint: ignore[imprecise-annotation] # generic backend command transport
) -> tuple[Any, str, str]: # simplint: ignore[imprecise-annotation] # public transport type
"""
Send a command to the backend.
:param cmd: the command to send
:param kwargs: keyword arguments to the backend
:returns: a tuple of: backend response, standard output text, standard error text
"""
return self._send(cmd, **kwargs)
class SubprocessCmdStatus(CmdStatus, Thread): # simplint: ignore[unexported-public-name] # internal worker status
def __init__(self, process: Popen[str], msg: str | None = None) -> None:
super().__init__()
self.process = process
self._msg = msg
self._out_err: tuple[str, str] | None = None
self.start()
@property
def done(self) -> bool:
# communicate() sets returncode before run() stores what it returned, so a caller polling the process can
# reach out_err() while it still holds None. Free-threaded builds land in that window; report the command
# finished only once its output is actually there.
return self._out_err is not None
def run(self) -> None:
self._out_err = self.process.communicate(input=self._msg)
def out_err(self) -> tuple[str, str]:
return cast("tuple[str, str]", self._out_err)
__all__ = [
"SubprocessFrontend",
]