蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行本章核心实例

PYTHON本地 Python 环境python-venv.py
python-venv.py219 行
"""蓝色天空网 mbsky.com | Create disposable Windows environments and install owned wheels offline."""
from base64 import urlsafe_b64encode
from hashlib import sha256
import json
import os
from pathlib import Path
import subprocess
import sys
from tempfile import TemporaryDirectory, gettempdir
from zipfile import ZipFile, ZIP_DEFLATED

sys.path.insert(0, str(Path(__file__).resolve().parent))
from mbsky_pychecks import Checks


INSPECT = """
import importlib.util, json, os, site, sys
print(json.dumps(dict(
    prefix=sys.prefix, base_prefix=sys.base_prefix, executable=sys.executable,
    version=sys.version.split()[0], pip=importlib.util.find_spec('pip') is not None,
    package_path=site.getsitepackages(), marker=os.environ.get('MBSKY_VENV_FIXTURE'),
    virtual_env=os.environ.get('VIRTUAL_ENV'))))
"""


def subprocess_environment():
    env = {name: value for name, value in os.environ.items()
           if not name.upper().startswith(("PIP_", "PYTHON"))
           and name.upper() not in ("VIRTUAL_ENV", "VIRTUAL_ENV_PROMPT")}
    env.update(PIP_CONFIG_FILE=os.devnull, PIP_NO_INDEX="1", PIP_DISABLE_PIP_VERSION_CHECK="1",
               PIP_NO_INPUT="1", PIP_NO_CACHE_DIR="1", MBSKY_VENV_FIXTURE="inherited",
               GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull)
    env["PATH"] = str(Path(sys.executable).parent) + os.pathsep + env["PATH"]
    return env


def run(args, workspace, env):
    result = subprocess.run(args, cwd=workspace, env=env, text=True, encoding="utf8",
                            errors="replace", capture_output=True, timeout=60)
    if result.returncode:
        raise RuntimeError((args, result.returncode, result.stdout, result.stderr))
    return result.stdout.strip()


def make_wheel(directory, package, version, output):
    info = f"{package}-{version}.dist-info"
    files = {
        package + "/__init__.py": f"VERSION = {version!r}\nRESULT = {output!r}\n".encode(),
        info + "/METADATA": f"Metadata-Version: 2.1\nName: {package}\nVersion: {version}\n".encode(),
        info + "/WHEEL": b"Wheel-Version: 1.0\nGenerator: mbsky-venv-lab\nRoot-Is-Purelib: true\nTag: py3-none-any\n",
    }
    manifest = [f"{name},sha256={urlsafe_b64encode(sha256(data).digest()).decode().rstrip('=')},{len(data)}"
                for name, data in files.items()]
    files[info + "/RECORD"] = ("\n".join(manifest + [info + "/RECORD,,"]) + "\n").encode()
    wheel = directory / f"{package}-{version}-py3-none-any.whl"
    with ZipFile(wheel, "w", ZIP_DEFLATED) as archive:
        for name, data in files.items():
            archive.writestr(name, data)
    with ZipFile(wheel) as archive:
        assert archive.testzip() is None
    return dict(name=wheel.name, sha256=sha256(wheel.read_bytes()).hexdigest())


def verify_shells(checks, workspace, env, path):
    powershell = r"""
$ErrorActionPreference = 'Stop'
$before = (Get-Command python -CommandType Application | Select-Object -First 1 -ExpandProperty Source)
$beforePath = $env:Path
. .\.venv\Scripts\Activate.ps1
$after = (Get-Command python -CommandType Application | Select-Object -First 1 -ExpandProperty Source)
$active = $env:VIRTUAL_ENV
$pipPath = (Get-Command pip -CommandType Application | Select-Object -First 1 -ExpandProperty Source)
deactivate
$restored = (Get-Command python -CommandType Application | Select-Object -First 1 -ExpandProperty Source)
[ordered]@{before=$before; after=$after; active=$active; pip=$pipPath; restored=$restored; pathRestored=($env:Path -ceq $beforePath)} | ConvertTo-Json -Compress
"""
    ps = json.loads(run(["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", powershell],
                        workspace, env))
    checks.eq("PowerShell activation resolves venv executable", str(Path(ps["after"]).resolve()), str(path))
    checks.eq("PowerShell VIRTUAL_ENV", str(Path(ps["active"]).resolve()), str(workspace / ".venv"))
    checks.eq("PowerShell pip is environment launcher", str(Path(ps["pip"]).resolve().parent), str(path.parent))
    checks.eq("PowerShell restores previous command", ps["restored"], ps["before"])
    checks.eq("PowerShell restores exact PATH", ps["pathRestored"], True)
    cmd = workspace / "observe.cmd"
    cmd.write_text(r"""@echo off
where.exe python
echo ===ACTIVE===
call ".venv\Scripts\activate.bat"
if errorlevel 1 exit /b 1
where.exe python
echo ===RESTORED===
call ".venv\Scripts\deactivate.bat"
if errorlevel 1 exit /b 1
where.exe python
""", encoding="ascii")
    before, remainder = run(["cmd.exe", "/d", "/c", cmd.name], workspace, env).split("===ACTIVE===")
    active, restored = remainder.split("===RESTORED===")
    checks.eq("CMD where first result is environment", str(Path(active.strip().splitlines()[0]).resolve()),
              str(path))
    checks.eq("CMD restores command resolution", restored.strip().splitlines(), before.strip().splitlines())


def main():
    if os.name != "nt":
        raise SystemExit("This checked lab uses Windows CMD and PowerShell. See the lesson for POSIX commands.")
    checks = Checks()
    env = subprocess_environment()
    temp_parent = Path(gettempdir()).resolve()
    with TemporaryDirectory(prefix="mbsky venv ", dir=temp_parent) as directory:
        workspace = Path(directory).resolve()
        assert workspace.parent == temp_parent and workspace.name.startswith("mbsky venv ")
        base = Path(sys._base_executable).resolve()
        version = run([str(base), "--version"], workspace, env)
        checks.eq("version of selected base executable", version, "Python " + sys.version.split()[0])

        def create(name, *options):
            target = workspace / name
            run([str(base), "-I", "-m", "venv", *options, str(target)], workspace, env)
            return (target / "Scripts/python.exe").resolve()

        left = create(".venv")
        right = create("second-env")
        empty = create("without-pip", "--without-pip")
        shared = create("shared-env", "--without-pip", "--system-site-packages")
        first = json.loads(run([str(left), "-I", "-c", INSPECT], workspace, env))
        without = json.loads(run([str(empty), "-I", "-c", INSPECT], workspace, env))
        inherited = json.loads(run([str(shared), "-I", "-c", INSPECT], workspace, env))
        checks.eq("default interpreter retains base version", first["version"], sys.version.split()[0])
        checks.eq("direct executable identifies its environment", first["executable"], str(left))
        checks.eq("prefix identifies environment", first["prefix"], str(workspace / ".venv"))
        checks.eq("base prefix matches existing Python installation", first["base_prefix"], sys.base_prefix)
        checks.eq("prefixes differ without shell activation", first["prefix"] != first["base_prefix"], True)
        checks.eq("direct execution needs no VIRTUAL_ENV", first["virtual_env"], None)
        checks.eq("ordinary environment variable is inherited", first["marker"], "inherited")
        checks.eq("default venv bootstraps pip", first["pip"], True)
        checks.eq("without-pip omits pip", without["pip"], False)
        target_lib = workspace / ".venv/Lib/site-packages"
        system_lib = Path(first["base_prefix"]) / "Lib/site-packages"
        checks.eq("default environment excludes base package directory",
                  str(system_lib).casefold() in [p.casefold() for p in first["package_path"]], False)
        checks.eq("system-site-packages includes base package directory",
                  str(system_lib).casefold() in [p.casefold() for p in inherited["package_path"]], True)
        checks.eq("Windows expected layout", all(p.is_file() for p in (
            left, left.parent / "activate.bat", left.parent / "Activate.ps1", left.parent / "pip.exe")), True)
        checks.eq("Windows own site-packages exists", target_lib.is_dir(), True)
        cfg = dict(line.split(" = ", 1) for line in (workspace / ".venv/pyvenv.cfg").read_text().splitlines()
                   if " = " in line)
        checks.eq("cfg points to base location", str(Path(cfg["home"]).resolve()), str(base.parent))
        checks.eq("cfg default isolation flag", cfg["include-system-site-packages"], "false")
        launch_bytes = (left.parent / "pip.exe").read_bytes()
        checks.eq("pip launcher contains absolute interpreter path", str(left).encode() in launch_bytes, True)
        verify_shells(checks, workspace, env, left)

        wheel_dir = workspace / "wheels"
        wheel_dir.mkdir()
        wheels = [make_wheel(wheel_dir, "mbsky_scene", "1.0", "dock"),
                  make_wheel(wheel_dir, "mbsky_scene", "2.0", "yard"),
                  make_wheel(wheel_dir, "mbsky_label", "1.0", "tag")]

        def pip(python, *args):
            return run([str(python), "-I", "-m", "pip", *args], workspace, env)

        def install(python, *args):
            return pip(python, "install", "--no-index", "--find-links", str(wheel_dir), *args)

        def inspect_package(python):
            return json.loads(run([str(python), "-I", "-c",
                                   "import json, mbsky_scene as s; print(json.dumps([s.VERSION,s.RESULT]))"],
                                  workspace, env))

        absent = "import importlib.util; print(importlib.util.find_spec('mbsky_scene'))"
        checks.eq("base has no owned package before install", run([str(base), "-I", "-c", absent], workspace, env),
                  "None")
        install(left, "mbsky_scene==1.0", "mbsky_label==1.0")
        install(right, "mbsky_scene==2.0")
        checks.eq("two environments import incompatible versions",
                  (inspect_package(left), inspect_package(right)), (["1.0", "dock"], ["2.0", "yard"]))
        checks.eq("base still cannot import owned package", run([str(base), "-I", "-c", absent], workspace, env),
                  "None")
        shown = dict(line.split(": ", 1) for line in pip(left, "show", "mbsky_scene").splitlines()
                     if ": " in line)
        checks.eq("pip show version and environment install location",
                  (shown["Version"], str(Path(shown["Location"]).resolve())), ("1.0", str(target_lib)))
        listed = {row["name"]: row["version"] for row in json.loads(pip(left, "list", "--format=json"))}
        checks.eq("pip list verifies both installed packages", (listed["mbsky_scene"], listed["mbsky_label"]),
                  ("1.0", "1.0"))
        requirements = workspace / "requirements.txt"
        requirements.write_text(pip(left, "freeze") + "\n", encoding="utf8")
        checks.eq("freeze records both exact package pins", set(requirements.read_text().splitlines()),
                  {"mbsky_label==1.0", "mbsky_scene==1.0"})
        install(left, "--upgrade", "mbsky_scene")
        checks.eq("offline upgrade changes chosen package", inspect_package(left), ["2.0", "yard"])
        recreated = create("recreated-env")
        install(recreated, "-r", str(requirements))
        checks.eq("clean environment recreated from frozen pins", inspect_package(recreated), ["1.0", "dock"])
        checks.eq("freeze matches after offline rebuild", pip(recreated, "freeze"), requirements.read_text().strip())

        ignore_patterns = [".venv/", "__pycache__/", "*.pyc", ".env", "*.egg-info/"]
        (workspace / ".gitignore").write_text("\n".join(ignore_patterns) + "\n", encoding="utf8")
        run(["git", "init", "-q"], workspace, env)
        ignored = [".venv/Scripts/python.exe", "__pycache__/x", "script.pyc", ".env", "demo.egg-info/PKG-INFO"]
        checks.eq("git applies each ignore rule", run(["git", "check-ignore", *ignored], workspace, env).splitlines(),
                  ignored)
        checks.eq("dependency manifest is not ignored",
                  run(["git", "check-ignore", "--non-matching", "-v", ".env", "requirements.txt"],
                      workspace, env).splitlines()[-1], "::\trequirements.txt")
        size = sum(file.stat().st_size for file in (workspace / "without-pip").rglob("*") if file.is_file())
        checks.eq("measured no-pip environment bytes positive", size > 0, True)
    checks.eq("owned temporary directory cleaned after shell exit", workspace.exists(), False)
    checks.finish("python-venv", runtime=sys.version, operating_system=sys.platform, wheel_fixtures=wheels,
                  without_pip_file_bytes=size, tested_shells=["Windows PowerShell", "CMD"],
                  package_transport="owned wheels with --no-index; no network",
                  untested=["POSIX activation", "Python 3.8", "virtualenv", "conda", "Django commands",
                            "external index", "pip self-upgrade"])


if __name__ == "__main__":
    main()
本例需在 本地 Python 环境 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:本地 Python 环境

入口文件:projects/python-lab/python-venv.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 python-venv.py,或下载右侧课程工程包。
  2. 确认本地已准备 本地 Python 环境。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习