示例工程 28-packaging-distribution

28-packaging-distribution/02-entry-point-cli/entry_point_cli.py

python · 2.2 KB

"""从 wheel 读取 entry point,并直接调用入口函数(不安装)。"""
 
from __future__ import annotations
 
import os
import shutil
import subprocess
import sys
import tempfile
import zipfile
from pathlib import Path
 
PYPROJECT = """\
[build-system]
requires = ["uv_build>=0.9,<0.14"]
build-backend = "uv_build"
 
[project]
name = "demo-cli"
version = "0.1.0"
requires-python = ">=3.12"
 
[project.scripts]
demo = "demo_cli:main"
"""
 
INIT = """\
def main() -> None:
    print("hello from entry point")
"""
 
 
def uv_available() -> bool:
    return shutil.which("uv") is not None
 
 
def entry_target(wheel: Path) -> str:
    with zipfile.ZipFile(wheel) as archive:
        name = next(item for item in archive.namelist() if item.endswith("entry_points.txt"))
        text = archive.read(name).decode()
    for line in text.splitlines():
        if "=" in line:
            return line.split("=", 1)[1].strip()
    raise ValueError("no entry point")
 
 
def run_entry() -> str:
    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        (root / "src" / "demo_cli").mkdir(parents=True)
        (root / "pyproject.toml").write_text(PYPROJECT, encoding="utf-8")
        (root / "src" / "demo_cli" / "__init__.py").write_text(INIT, encoding="utf-8")
        result = subprocess.run(
            ["uv", "build", "--wheel", "--offline"],
            cwd=root,
            capture_output=True,
            text=True,
            check=False,
        )
        if result.returncode != 0:
            raise RuntimeError(result.stderr)
        wheel = next((root / "dist").glob("*.whl"))
        target = entry_target(wheel)
        module, function = target.split(":")
        env = os.environ.copy()
        env["PYTHONPATH"] = str(wheel)
        process = subprocess.run(
            [sys.executable, "-c", f"from {module} import {function}; {function}()"],
            capture_output=True,
            text=True,
            env=env,
            check=False,
        )
        if process.returncode != 0:
            raise RuntimeError(process.stderr)
        return process.stdout.strip()
 
 
def main() -> None:
    if not uv_available():
        print("uv: missing")
        return
    print(f"entry output: {run_entry()}")
 
 
if __name__ == "__main__":
    main()