蓝色天空网mbsky.com · 知识 · 实践 · 创造Python · 本地阅读预览
教程 / Python / 数据科学 / Python

Python pip:安装软件包与重建实验环境

用两个临时环境离线安装、查看、导出和卸载软件包,理解 requirements 文件的边界。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

先确定 pip 属于哪个解释器

pip 安装和管理 Python 软件包。PyPI 是常见的软件包索引。pip 也可以从本地 wheel 目录安装。先为项目建立虚拟环境,再用其中的解释器运行 python -m pip --version。输出会注明 pip 的版本、安装路径和关联的 Python 版本。

Python 2.7.9 和 3.4 是 CPython 默认引导 pip 的历史节点。精简发行版或以 --without-pip 创建的环境仍可能没有 pip。若当前解释器提供 ensurepip,可用 python -m ensurepip 安装随解释器附带的 pip。若发行版省略 ensurepip,按该发行版的说明安装。

下载、安装、查看和卸载

在虚拟环境里用 python -m pip install numpy 安装 NumPy。python -m pip list 查看当前环境中的发行包。要只下载而暂不安装,可以用 pip download。手头有一组已核对的 wheel 时,可用 --no-index --find-links 指定本地目录。

python -m pip uninstall numpy 从当前环境卸载 NumPy。一般会先询问是否继续,自动化实验使用 -y。卸载一个包可能留下它的依赖,也可能让依赖它的其他包出现缺项。用 pip check 查看环境是否存在依赖错误。

本站实验创建两个临时环境和两份自编 wheel,验证按名字选择版本、下载文件、安装依赖、实际导入和卸载。另在同一隔离流程中用官方 NumPy wheel 验证了安装、数组计算和卸载。

保存依赖列表,再验证重建

python -m pip freeze > requirements.txt 保存当前可见的安装记录。Python 3.12 及以后的默认省略项是 pip,较早 Python 的规则还涉及其它引导工具,需结合 pip 版本核对。本站在 CPython 3.12.14 新建空环境,pip list 显示 pip 25.0.1,默认 freeze 输出为空,freeze --all 输出 pip==25.0.1。把默认结果存成 requirements.txt 并离线执行安装后,pip check 仍成功。空清单可以对应一个已经安装 pip 的环境。freeze 反映已安装状态,完整重建还要记录解释器、平台和所用包文件。

在另一个虚拟环境中运行 python -m pip install -r requirements.txt,再用 pip check 和实际导入核验。requirements 文件是当前已安装包的记录。解释器版本、系统架构、二进制依赖、包索引或构建选项改变,都可能影响重建结果。需要限制所用文件时可固定版本并校验 wheel 的 SHA256。

将本站实验和核对模块放在同一目录,运行 python python3-pip.py。实验生成本地 wheel 并自动清理临时目录。若要加入 NumPy 分支,可传 --numpy-wheel 和对应的 --numpy-sha256,选择适合当前 Python 和操作系统的官方 wheel。

下载 pip 离线重建实验

所需环境:本地 Python 3 和 ensurepip

当前源码 SHA256:1940f334d846a1fcfec7dd097cd526b8727d79b2f8c59c84a18bc2f4fa743169

下载本站示例源码
下载运行结果核对模块

所需环境:本地 Python 3 和 ensurepip

当前源码 SHA256:4b803aca5654715f4eabe59fc1b3ada5a00337edbe21e80d5009c5195b2c8b4a

下载本站示例源码

了解 Anaconda 与 conda

Anaconda 是面向科学计算的发行版,通常提供 Python、conda 和一组数据科学工具。conda 可创建和切换环境,也能安装 Python 解释器与其他二进制依赖。pip 则通过指定的解释器管理 Python 发行包。二者各有自己的软件包来源与环境清单。

在 conda 环境里使用 pip 前先确定当前环境,再用其中的 python -m pip。conda 的环境导出可记录渠道与环境包。本站本章实测使用的是 venv 与 pip,Anaconda 安装器和 conda 环境切换另按对应平台说明。

pip 常见操作

任务命令观察结果
确认解释器归属python -m pip --version版本、模块路径和关联 Python 版本。
查看可用版本python -m pip index versions PACKAGE由指定索引或 wheel 目录提供的可用版本。
下载但暂不安装python -m pip download PACKAGE得到适配当前目标的文件及所需依赖。
安装python -m pip install PACKAGE将匹配版本及所需依赖安装到当前环境。
查看已安装发行包python -m pip list列出包名和版本。脚本可用 --format=json。
导出安装记录python -m pip freeze > requirements.txt以 requirements 格式输出当前安装记录。
按记录重装python -m pip install -r requirements.txt按文件中记录的要求解析并安装。
检查依赖python -m pip check检查已安装包所需依赖是否缺失或版本不符。
卸载python -m pip uninstall PACKAGE删除当前环境中的指定发行包。

本章自编源码与运行范围

Python · 阅读源码
"""蓝色天空网 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 环境

当前源码 SHA256:1940f334d846a1fcfec7dd097cd526b8727d79b2f8c59c84a18bc2f4fa743169

下载本站示例源码

当前源码有命名范围的实际运行记录;原文全部事实、其它平台和IDE界面仍待逐项验收。

常见错误与边界

  • 命令、源码、当前解释器和具体平台分别核对,不能以单项运行推断整章验收。

练习与解答

使用本站实例修改一个条件,先写下预期,再实际运行。

展开参考解答

比较原始输出、修改后的输出及错误类型;未执行的平台和界面继续单列。

规范与官方依据