Skip to content

Creating a venv can run a local ensurepip.py #160279

Open

Description

@jelle-openai

Bug report

When you run python -m venv .venv, and .venv/ensurepip.py already exists, the file gets run.

Repro script:

import os
from pathlib import Path
import subprocess
import sys
from tempfile import TemporaryDirectory

with TemporaryDirectory() as name:
    root = Path(name)
    home = root / "private"
    home.mkdir(mode=0o700)
    env = {k: v for k, v in os.environ.items() if not k.startswith("PYTHON")}
    env["PIP_NO_INDEX"] = "1"
    cases = [
        ("normal", [], [], True),
        ("isolated", ["-I"], [], True),
        ("without-pip", ["-I"], ["--without-pip"], False),
        ("clear-regular-directory", ["-I"], ["--clear"], False),
    ]
    if len(sys.argv) > 1:
        cases.append(("vscode", ["-I"], [], True))
    for case, interpreter_options, venv_options, expected in cases:
        project = root / case
        target = project / ".venv"
        target.mkdir(parents=True)
        marker = home / case
        (target / "ensurepip.py").write_text(
            "import os, runpy, sys\n"
            "from pathlib import Path\n"
            f"Path({str(marker)!r}).write_text('bootstrap executed')\n"
            "sys.path[:] = [s for s in sys.path if os.path.realpath(s) != os.getcwd()]\n"
            "runpy.run_module('ensurepip', run_name='__main__')\n"
        )
        if case == "vscode":
            arguments = [str(Path(sys.argv[1]).resolve())]
        else:
            arguments = ["-m", "venv", *venv_options, ".venv"]
        command = [sys.executable, *interpreter_options, *arguments]
        subprocess.run(command, env=env, cwd=project, check=True, timeout=90)
        print(case, "marker", marker.exists(), flush=True)
        assert marker.exists() is expected

CPython versions tested on:

3.12, 3.13, CPython main branch

Operating systems tested on:

macOS, Linux

Linked PRs

Activity

  1. added
    stdlibStandard Library Python modules in the Lib/ directory
    topic-venvRelated to the venv module
    on Oct 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytopic-venvRelated to the venv moduletype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions