"""蓝色天空网 mbsky.com · 两个临时环境中的离线 pip 实验。"""
from argparse import ArgumentParser
from base64 import urlsafe_b64encode
from hashlib import sha256
import json
import os
from pathlib import Path
import platform
import re
import subprocess
import sys
from tempfile import TemporaryDirectory
from zipfile import ZIP_DEFLATED, ZipFile, ZipInfo
sys.path.insert(0, str(Path(__file__).resolve().parent))
from mbsky_pychecks import Checks
VERSION = "1.0.0"
PROJECT = "mbsky-pip-report"
DEPENDENCY = "mbsky-pip-units"
ENVIRONMENT = {key: value for key, value in os.environ.items() if not key.upper().startswith("PIP_")}
ENVIRONMENT["PIP_CONFIG_FILE"] = os.devnull
ENVIRONMENT["PIP_DISABLE_PIP_VERSION_CHECK"] = "1"
def digest(path):
return sha256(path.read_bytes()).hexdigest()
def write_wheel(folder, project, source, requires=None):
module = project.replace("-", "_")
info = f"{module}-{VERSION}.dist-info"
metadata = f"Metadata-Version: 2.1\nName: {project}\nVersion: {VERSION}\n"
if requires:
metadata += f"Requires-Dist: {requires} (=={VERSION})\n"
files = {
f"{module}/__init__.py": source.encode("utf-8"),
f"{info}/METADATA": (metadata + "\n").encode("utf-8"),
f"{info}/WHEEL": b"Wheel-Version: 1.0\nGenerator: mbsky-pip-lab\nRoot-Is-Purelib: true\nTag: py3-none-any\n",
}
record_name = f"{info}/RECORD"
rows = []
for name, payload in files.items():
encoded = urlsafe_b64encode(sha256(payload).digest()).rstrip(b"=").decode("ascii")
rows.append(f"{name},sha256={encoded},{len(payload)}")
files[record_name] = ("\n".join(rows + [record_name + ",,"]) + "\n").encode("utf-8")
wheel = folder / f"{module}-{VERSION}-py3-none-any.whl"
with ZipFile(wheel, "w", compression=ZIP_DEFLATED) as package:
for name, payload in files.items():
member = ZipInfo(name, (2026, 1, 1, 0, 0, 0))
member.compress_type = ZIP_DEFLATED
package.writestr(member, payload)
with ZipFile(wheel) as package:
assert package.testzip() is None
return wheel
def run(python, *args, expect_success=True):
result = subprocess.run([str(python), "-I", "-B", "-X", "utf8", *map(str, args)],
env=ENVIRONMENT, capture_output=True, text=True, encoding="utf-8",
timeout=90)
if (result.returncode == 0) != expect_success:
raise RuntimeError(f"Unexpected result for {args}: {result.returncode}\n{result.stdout}\n{result.stderr}")
return result
def pip(python, *args, expect_success=True):
return run(python, "-m", "pip", "--isolated", "--disable-pip-version-check", "--no-cache-dir",
*args, expect_success=expect_success)
def create_environment(folder, check, label):
run(sys.executable, "-m", "venv", "--without-pip", folder)
python = folder / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
before = run(python, "-c", "from importlib.util import find_spec;print(find_spec('pip') is None)")
check.eq(label + " starts without pip", before.stdout.strip(), "True")
run(python, "-m", "ensurepip", "--upgrade")
report = pip(python, "--version").stdout.strip()
check.eq(label + " pip belongs to its own interpreter", str(folder).casefold() in report.casefold(), True)
version = pip(python, "list", "--format=json").stdout
check.eq(label + " bootstrap starts with pip only",
[package["name"] for package in json.loads(version) if package["name"] != "setuptools"], ["pip"])
return python, report.split()[1]
def import_report(python):
return run(python, "-c", "from mbsky_pip_report import describe;print(describe(4))").stdout.strip()
def verify_numpy(check, python, wheel, expected_sha):
check.eq("NumPy wheel matches supplied SHA256", digest(wheel), expected_sha)
pip(python, "install", "--no-index", "--only-binary=:all:", wheel)
result = run(python, "-c", "import numpy as np;print(np.__version__);print(int(np.dot([1,2],[3,4])))")
version, value = result.stdout.splitlines()
check.eq("NumPy installation runs an actual array operation", value, "11")
check.eq("pip list reports installed NumPy version",
{item["name"]: item["version"] for item in json.loads(pip(python, "list", "--format=json").stdout)}["numpy"],
version)
pip(python, "uninstall", "-y", "numpy")
absent = run(python, "-c", "import numpy", expect_success=False)
check.eq("NumPy import fails after uninstall", "No module named 'numpy'" in absent.stderr, True)
return version
def experiment(check, root, numpy_wheel, numpy_sha):
wheelhouse = root / "wheelhouse"
wheelhouse.mkdir()
unit = write_wheel(wheelhouse, DEPENDENCY, "def pack(count):\n return count * 25\n")
app = write_wheel(wheelhouse, PROJECT, "from mbsky_pip_units import pack\n\ndef describe(count):\n return f'{pack(count)} samples'\n",
requires=DEPENDENCY)
first, pip_version = create_environment(root / "first", check, "first environment")
second, other_version = create_environment(root / "second", check, "second environment")
check.eq("both isolated pips share the bootstrap version", other_version, pip_version)
local = ["--no-index", "--find-links", str(wheelhouse)]
spec = f"{PROJECT}=={VERSION}"
versions = pip(first, "index", "versions", PROJECT, *local).stdout
check.eq("index lists fixture version from local wheelhouse", "Available versions: " + VERSION in versions, True)
download = root / "download"
download.mkdir()
pip(first, "download", *local, "--only-binary=:all:", "--dest", download, spec)
expected = {item.name: digest(item) for item in (app, unit)}
check.eq("pip download retrieves both exact wheel files",
{item.name: digest(item) for item in sorted(download.iterdir())}, dict(sorted(expected.items())))
check.eq("download did not install fixture",
PROJECT not in pip(first, "list", "--format=json").stdout, True)
pip(first, "install", *local, "--only-binary=:all:", spec)
check.eq("installed application calls its dependency", import_report(first), "100 samples")
packages = {item["name"]: item["version"] for item in json.loads(pip(first, "list", "--format=json").stdout)}
check.eq("list includes requested package and resolved dependency",
{name: packages[name] for name in (PROJECT, DEPENDENCY)}, {PROJECT: VERSION, DEPENDENCY: VERSION})
check.eq("pip check accepts resolved dependency", pip(first, "check").returncode, 0)
freeze = pip(first, "freeze").stdout
requirement_file = root / "requirements.txt"
requirement_file.write_text(freeze, encoding="utf-8", newline="\n")
check.eq("freeze lists installed packages in requirements form",
freeze.splitlines(), [f"{PROJECT}=={VERSION}", f"{DEPENDENCY}=={VERSION}"])
check.eq("freeze all includes bootstrap pip", f"pip=={pip_version}" in pip(first, "freeze", "--all").stdout.splitlines(), True)
check.eq("second environment initially lacks the first package",
PROJECT not in pip(second, "list", "--format=json").stdout, True)
pip(second, "install", *local, "--only-binary=:all:", "-r", requirement_file)
check.eq("install from requirements recreates the observed package set", pip(second, "freeze").stdout, freeze)
check.eq("recreated program executes", import_report(second), "100 samples")
pinned = root / "hashes.txt"
pinned.write_text(f"{spec} --hash=sha256:{digest(app)}\n{DEPENDENCY}=={VERSION} --hash=sha256:{digest(unit)}\n",
encoding="utf-8", newline="\n")
pip(second, "install", *local, "--only-binary=:all:", "--require-hashes", "--force-reinstall", "-r", pinned)
check.eq("hash-pinned installation remains functional", import_report(second), "100 samples")
pinned.write_text(pinned.read_text(encoding="utf-8").replace(digest(app), "0" * 64), encoding="utf-8")
rejected = pip(second, "install", *local, "--only-binary=:all:", "--require-hashes",
"--force-reinstall", "-r", pinned, expect_success=False)
check.eq("wrong wheel SHA256 blocks installation", "do not match the hashes" in rejected.stderr.casefold(), True)
check.eq("existing environment still works after hash rejection", import_report(second), "100 samples")
pip(first, "uninstall", "-y", DEPENDENCY)
broken = pip(first, "check", expect_success=False)
check.eq("pip check detects missing dependency", DEPENDENCY in broken.stdout, True)
pip(first, "uninstall", "-y", PROJECT)
missing = run(first, "-c", "import mbsky_pip_report", expect_success=False)
check.eq("uninstall makes the package no longer importable", "No module named 'mbsky_pip_report'" in missing.stderr, True)
check.eq("uninstall in first environment leaves second working", import_report(second), "100 samples")
numpy_version = verify_numpy(check, first, numpy_wheel, numpy_sha) if numpy_wheel else None
return pip_version, expected, freeze.splitlines(), numpy_version
def main():
parser = ArgumentParser(description="Create and discard two temporary offline pip environments.")
parser.add_argument("--numpy-wheel", type=Path)
parser.add_argument("--numpy-sha256")
args = parser.parse_args()
if bool(args.numpy_wheel) != bool(args.numpy_sha256):
parser.error("Provide both the official wheel and its published SHA256.")
if args.numpy_wheel:
if not args.numpy_wheel.name.startswith("numpy-") or args.numpy_wheel.suffix != ".whl":
parser.error("Specify an official NumPy wheel compatible with this Python.")
if not re.fullmatch("[0-9a-fA-F]{64}", args.numpy_sha256):
parser.error("Provide a 64-digit SHA256.")
check = Checks()
with TemporaryDirectory(prefix="mbsky-pip-") as temp:
root = Path(temp)
version, hashes, frozen, numpy = experiment(
check, root, args.numpy_wheel.resolve() if args.numpy_wheel else None,
args.numpy_sha256.lower() if args.numpy_sha256 else None)
check.eq("temporary environments cleaned up", root.exists(), False)
check.finish("python3-pip", python=platform.python_version(), platform=platform.platform(),
pip=version, numpy=numpy, owned_wheel_sha256=hashes, freeze=frozen,
network=False, source_requests=0)
if __name__ == "__main__":
main()
本例需在 本地 Python 3 和 ensurepip 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:本地 Python 3 和 ensurepip
入口文件:projects/python-lab/python3-pip.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
python3-pip.py,或下载右侧课程工程包。 - 确认本地已准备 本地 Python 3 和 ensurepip。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip