Python’s ensurepip module installs pip from bundled wheel files without requiring network access — it ships a pinned pip wheel inside the stdlib itself. import ensurepip. Version: ensurepip.version() → str — the version of pip bundled with this Python installation (e.g. "24.0"). Bootstrap: ensurepip.bootstrap(root=None, upgrade=False, user=False, altinstall=False, default_pip=True, verbosity=0) — installs pip (and setuptools on older Pythons) from the bundled wheels; upgrade=True upgrades an existing pip; root installs into an alternate root (for staged/chroot installs); user=True installs into site.getusersitepackages(); altinstall=True installs pip3.X but not the plain pip/pip3 aliases (avoids conflicts in multi-version setups). Idempotent guard: if pip is already present and upgrade=False, bootstrap does nothing. Used by venv.create(with_pip=True) internally. Claude Code generates pip-bootstrapped environment provisioners, CI setup scripts, embedded interpreter setups, and offline-capable distribution bundles.
CLAUDE.md for ensurepip
## ensurepip Stack
- Stdlib: import ensurepip
- Version: ensurepip.version() # bundled pip version string
- Install: ensurepip.bootstrap() # install pip if missing
- Upgrade: ensurepip.bootstrap(upgrade=True) # upgrade existing pip
- Root: ensurepip.bootstrap(root="/stage") # staged install
- CLI: python -m ensurepip --upgrade # same from the shell
- Note: venv.create(with_pip=True) calls ensurepip.bootstrap() internally
ensurepip Bootstrap Pipeline
# app/ensurepiputil.py — bootstrap, check, provision, offline installer
from __future__ import annotations
import importlib.util
import subprocess
import sys
import ensurepip
from dataclasses import dataclass
from pathlib import Path
# ─────────────────────────────────────────────────────────────────────────────
# 1. pip state inspection
# ─────────────────────────────────────────────────────────────────────────────
def bundled_pip_version() -> str:
"""
Return the pip version string bundled with this Python installation.
Example:
print(bundled_pip_version()) # "24.0"
"""
return ensurepip.version()
def installed_pip_version(python: "str | Path | None" = None) -> "str | None":
"""
Return the version of pip currently installed in the target python,
or None if pip is not importable.
Example:
print(installed_pip_version()) # current interpreter
print(installed_pip_version(".venv/bin/python"))
"""
exe = str(python) if python else sys.executable
try:
result = subprocess.run(
[exe, "-m", "pip", "--version"],
capture_output=True, text=True, timeout=15,
)
if result.returncode == 0:
# "pip 24.0 from /path ..."
parts = result.stdout.split()
if len(parts) >= 2:
return parts[1]
except Exception:
pass
return None
def pip_is_installed(python: "str | Path | None" = None) -> bool:
"""
Return True if pip can be found in the target python environment.
Example:
if not pip_is_installed(".venv/bin/python"):
bootstrap_pip(".venv/bin/python")
"""
exe = str(python) if python else sys.executable
spec = importlib.util.find_spec("pip") if python is None else None
if python is None:
return spec is not None
try:
r = subprocess.run(
[exe, "-c", "import pip"],
capture_output=True, timeout=10,
)
return r.returncode == 0
except Exception:
return False
# ─────────────────────────────────────────────────────────────────────────────
# 2. Bootstrap helpers
# ─────────────────────────────────────────────────────────────────────────────
def bootstrap_pip(
upgrade: bool = False,
user: bool = False,
verbosity: int = 0,
) -> None:
"""
Ensure pip is installed in the current Python interpreter using ensurepip.
Example:
bootstrap_pip(upgrade=True)
"""
ensurepip.bootstrap(
upgrade=upgrade,
user=user,
verbosity=verbosity,
)
def bootstrap_pip_in_env(
env_dir: "str | Path",
upgrade: bool = False,
) -> subprocess.CompletedProcess:
"""
Bootstrap pip into a virtual environment by invoking the env's python
with '-m ensurepip'. This works even if the env was created without pip.
Example:
import venv
venv.create(".venv", with_pip=False)
bootstrap_pip_in_env(".venv")
"""
p = Path(env_dir)
if sys.platform == "win32":
python = p / "Scripts" / "python.exe"
else:
python = p / "bin" / "python"
cmd = [str(python), "-m", "ensurepip"]
if upgrade:
cmd.append("--upgrade")
return subprocess.run(cmd, check=True, capture_output=True)
def upgrade_pip_in_env(
env_dir: "str | Path",
) -> subprocess.CompletedProcess:
"""
Upgrade pip inside a virtual environment to the latest available version.
First bootstraps if pip is absent, then upgrades via pip itself.
Example:
upgrade_pip_in_env(".venv")
"""
p = Path(env_dir)
python = (
p / "Scripts" / "python.exe"
if sys.platform == "win32"
else p / "bin" / "python"
)
# Ensure pip is present
subprocess.run([str(python), "-m", "ensurepip", "--upgrade"],
check=True, capture_output=True)
# Upgrade to PyPI latest
return subprocess.run(
[str(python), "-m", "pip", "install", "--upgrade", "pip"],
check=True,
)
# ─────────────────────────────────────────────────────────────────────────────
# 3. Staged root install
# ─────────────────────────────────────────────────────────────────────────────
def bootstrap_pip_to_root(
root: "str | Path",
upgrade: bool = False,
) -> None:
"""
Bootstrap pip into an alternative root directory (for staged/chroot builds).
pip files are installed under {root}/lib/pythonX.Y/site-packages/.
Example:
bootstrap_pip_to_root("/mnt/chroot")
"""
ensurepip.bootstrap(root=str(root), upgrade=upgrade)
# ─────────────────────────────────────────────────────────────────────────────
# 4. Environment provisioner
# ─────────────────────────────────────────────────────────────────────────────
@dataclass
class PipProvisionResult:
"""
Result of ensuring pip is present and optionally upgraded.
Example:
result = provision_pip(".venv/bin/python")
print(result)
"""
python: str
was_installed: bool
was_upgraded: bool
bundled_version: str
installed_version: "str | None"
ok: bool
error: str
def __str__(self) -> str:
status = "OK" if self.ok else f"ERROR({self.error})"
action = "installed" if self.was_installed else ("upgraded" if self.was_upgraded else "already present")
return (
f"PipProvisionResult({self.python} {status} "
f"action={action} version={self.installed_version})"
)
def provision_pip(
python: "str | Path | None" = None,
upgrade: bool = False,
) -> PipProvisionResult:
"""
Ensure pip is present in the Python environment, bootstrapping if necessary.
Returns a structured result with what was done.
Example:
result = provision_pip(".venv/bin/python", upgrade=True)
print(result)
"""
exe = str(python) if python else sys.executable
bundled = bundled_pip_version()
initial_version = installed_pip_version(exe)
was_installed = False
was_upgraded = False
error = ""
try:
if not pip_is_installed(exe):
# Bootstrap pip
subprocess.run(
[exe, "-m", "ensurepip", "--upgrade" if upgrade else "--default-pip"],
check=True, capture_output=True,
)
was_installed = True
elif upgrade:
# Upgrade existing pip via pip install --upgrade pip
subprocess.run(
[exe, "-m", "pip", "install", "--upgrade", "pip"],
check=True, capture_output=True,
)
was_upgraded = True
final_version = installed_pip_version(exe)
return PipProvisionResult(
python=exe,
was_installed=was_installed,
was_upgraded=was_upgraded,
bundled_version=bundled,
installed_version=final_version,
ok=True,
error="",
)
except Exception as e:
return PipProvisionResult(
python=exe,
was_installed=was_installed,
was_upgraded=was_upgraded,
bundled_version=bundled,
installed_version=installed_pip_version(exe),
ok=False,
error=str(e),
)
# ─────────────────────────────────────────────────────────────────────────────
# 5. CI / scripted environment setup helper
# ─────────────────────────────────────────────────────────────────────────────
def setup_fresh_env(
env_dir: "str | Path",
packages: "list[str] | None" = None,
requirements: "str | Path | None" = None,
upgrade_pip: bool = True,
) -> dict:
"""
Create a fresh venv, bootstrap pip, optionally upgrade pip and install packages.
Returns a summary dict with paths and package count.
Example:
info = setup_fresh_env(
".ci-env",
packages=["pytest", "coverage"],
upgrade_pip=True,
)
print(info)
"""
import venv as _venv
p = Path(env_dir)
python = (
p / "Scripts" / "python.exe"
if sys.platform == "win32"
else p / "bin" / "python"
)
# Create env without pip first for fine-grained control
_venv.create(str(p), with_pip=False, clear=True)
# Bootstrap pip from bundled wheels (offline-safe)
subprocess.run(
[str(python), "-m", "ensurepip", "--default-pip"],
check=True, capture_output=True,
)
if upgrade_pip:
subprocess.run(
[str(python), "-m", "pip", "install", "--upgrade", "pip", "-q"],
check=True,
)
if requirements:
subprocess.run(
[str(python), "-m", "pip", "install", "-r", str(requirements), "-q"],
check=True,
)
if packages:
subprocess.run(
[str(python), "-m", "pip", "install", "-q"] + packages,
check=True,
)
pip_ver = installed_pip_version(python)
return {
"env_dir": str(p),
"python": str(python),
"pip_version": pip_ver,
"packages": packages or [],
}
# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────
if __name__ == "__main__":
import tempfile
print("=== ensurepip demo ===")
# ── bundled version ────────────────────────────────────────────────────────
print("\n--- bundled_pip_version ---")
print(f" bundled pip: {bundled_pip_version()}")
# ── installed version (current interpreter) ───────────────────────────────
print("\n--- installed_pip_version ---")
ver = installed_pip_version()
print(f" installed pip: {ver}")
# ── pip_is_installed ──────────────────────────────────────────────────────
print("\n--- pip_is_installed ---")
print(f" pip present: {pip_is_installed()}")
with tempfile.TemporaryDirectory() as td:
env_dir = Path(td) / ".test-env"
# ── setup_fresh_env ────────────────────────────────────────────────────
print("\n--- setup_fresh_env ---")
info = setup_fresh_env(env_dir, packages=[], upgrade_pip=False)
print(f" {info}")
# ── provision_pip ──────────────────────────────────────────────────────
print("\n--- provision_pip ---")
result = provision_pip(info["python"], upgrade=False)
print(f" {result}")
# ── pip version in env ────────────────────────────────────────────────
print("\n--- pip version in env ---")
env_ver = installed_pip_version(info["python"])
print(f" pip in env: {env_ver}")
# ── bootstrap to root ─────────────────────────────────────────────────
print("\n--- bootstrap_pip_to_root ---")
fake_root = Path(td) / "staged-root"
fake_root.mkdir()
try:
bootstrap_pip_to_root(fake_root)
# Check if files landed
lib_dirs = list(fake_root.rglob("pip"))
print(f" pip directories under root: {len(lib_dirs)}")
except Exception as e:
print(f" (skipped: {e})")
print("\n=== done ===")
For the pip command via subprocess alternative — subprocess.run([sys.executable, "-m", "pip", "install", ...]) installs packages into the current environment without involving ensurepip — use subprocess pip when pip is already present and you need to install specific packages; use ensurepip to guarantee pip exists before any pip commands can run, especially in environments created with with_pip=False, CI base images, or embedded Python builds that may not ship pip. For the get-pip.py (downloadable script) alternative — get-pip.py fetches the latest pip wheel from PyPI and installs it — use get-pip.py when you need a pip version newer than what ensurepip bundles; use ensurepip for offline or air-gapped setups where network access is unavailable, since ensurepip works entirely from bundled wheel files that ship as part of the Python stdlib. The Claude Skills 360 bundle includes ensurepip skill sets covering bundled_pip_version()/installed_pip_version()/pip_is_installed() inspection helpers, bootstrap_pip() current-interpreter bootstrapper, bootstrap_pip_in_env()/upgrade_pip_in_env() venv-targeted helpers, bootstrap_pip_to_root() staged-install helper, PipProvisionResult + provision_pip() structured provisioner, and setup_fresh_env() CI-oriented full environment setup. Start with the free tier to try pip bootstrap patterns and ensurepip pipeline code generation.