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

分别创建两个环境并离线安装本站 wheel

PYTHONWindows CPython 3.12.14、uv 0.10.8、python-dotenv 1.2.4 与隔离开发工具。env_lab.py
env_lab.py104 行
"""Create two isolated Python environments and install a self-authored offline wheel."""
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
from zipfile import ZipFile, ZipInfo


PACKAGE = "mbsky_env_probe"
VERSION = "0.1.0"
DIST = f"{PACKAGE}-{VERSION}.dist-info"


def fixture_wheel(root):
    target = root / f"{PACKAGE}-{VERSION}-py3-none-any.whl"
    files = {
        f"{PACKAGE}/__init__.py": b'"""Private local environment exercise."""\nMARKER = "mbsky-local"\n',
        f"{PACKAGE}/sample.txt": b"offline fixture\n",
        f"{DIST}/METADATA": (
            f"Metadata-Version: 2.1\nName: mbsky-env-probe\nVersion: {VERSION}\nRequires-Python: >=3.12\n\n"
        ).encode(),
        f"{DIST}/WHEEL": b"Wheel-Version: 1.0\nGenerator: mbsky-local-fixture\nRoot-Is-Purelib: true\nTag: py3-none-any\n",
    }
    record = []
    for name,data in sorted(files.items()):
        digest = urlsafe_b64encode(sha256(data).digest()).decode().rstrip("=")
        record.append(f"{name},sha256={digest},{len(data)}")
    files[f"{DIST}/RECORD"] = ("\n".join(record+[f"{DIST}/RECORD,,"])+"\n").encode()
    with ZipFile(target,"w") as archive:
        for name,data in sorted(files.items()):
            archive.writestr(ZipInfo(name,(2026,1,1,0,0,0)),data)
    return target


def interpreter(environment):
    return environment / ("Scripts/python.exe" if os.name=="nt" else "bin/python")


def exercise(uv):
    cases = []
    def observe(name, inputs, operation, expected, actual):
        assert expected == actual, (name,expected,actual)
        cases.append(dict(name=name,input=inputs,operation=operation,expected=expected,actual=actual))

    with TemporaryDirectory(prefix="mbsky-offline-env-") as temp:
        root = Path(temp)
        env = {key:value for key,value in os.environ.items()
               if key.lower() in {"systemroot","windir","path","pathext","systemdrive","comspec"}}
        env.update(PYTHONUTF8="1",PIP_CONFIG_FILE=os.devnull,PIP_DISABLE_PIP_VERSION_CHECK="1",
                   APPDATA=str(root),LOCALAPPDATA=str(root),TEMP=str(root),TMP=str(root),
                   UV_CACHE_DIR=str(root/"uv-cache"),UV_NO_CONFIG="1",UV_OFFLINE="1",
                   UV_PYTHON_DOWNLOADS="never")
        base = Path(sys._base_executable).resolve()

        def command(exe,*args):
            return subprocess.run([str(exe),*map(str,args)],cwd=root,env=env,encoding="utf8",
                                  capture_output=True,timeout=35,check=True).stdout.strip()

        native_dir, uv_dir = root/"native-env",root/"uv-env"
        command(sys.executable,"-I","-m","venv","--without-pip",native_dir)
        version = command(uv,"--version")
        command(uv,"--offline","venv","--python",base,uv_dir)
        native, uv_python = interpreter(native_dir),interpreter(uv_dir)
        probe = (
            "import importlib.util,json,sys; "
            "print(json.dumps([sys.version_info[:3],sys.prefix != sys.base_prefix,"
            "importlib.util.find_spec('mbsky_env_probe') is not None]))"
        )
        python_version = list(sys.version_info[:3])
        expect = [python_version,True,False]
        observe("env_two_interpreters",["venv --without-pip","uv --offline venv"],"Create and run each actual interpreter with -I",
                [expect,expect,True],[json.loads(command(native,"-I","-c",probe)),
                json.loads(command(uv_python,"-I","-c",probe)),native.resolve()!=uv_python.resolve()])

        wheel = fixture_wheel(root)
        command(uv,"--offline","pip","install","--no-index","--no-deps","--python",uv_python,wheel)
        verify = (
            "import importlib.metadata,importlib.resources,json,mbsky_env_probe; "
            "print(json.dumps([importlib.metadata.version('mbsky-env-probe'),mbsky_env_probe.MARKER,"
            "importlib.resources.files(mbsky_env_probe).joinpath('sample.txt').read_text(encoding='utf8')]))"
        )
        installed = [VERSION,"mbsky-local","offline fixture\n"]
        observe("env_uv_isolation","explicit uv target and self-authored wheel","Read actual package and resource in uv only",
                [installed,expect],[json.loads(command(uv_python,"-I","-c",verify)),json.loads(command(native,"-I","-c",probe))])

        command(sys.executable,"-I","-m","pip","--python",native,"install","--no-index","--no-deps",wheel)
        observe("env_pip_explicit_target","pip --python native-env","Use an explicit interpreter and verify distribution metadata and resource",
                installed,json.loads(command(native,"-I","-c",verify)))
        listing = command(sys.executable,"-I","-m","pip","--python",native,"list","--format=json")
        frozen = command(sys.executable,"-I","-m","pip","--python",native,"freeze")
        observe("env_pip_list_freeze","actual pip in the native environment",
                "Compare list output and freeze of a direct wheel install without exposing the temporary path",
                [installed[0],True],[next(r["version"] for r in json.loads(listing) if r["name"]=="mbsky-env-probe"),
                any(line.startswith("mbsky-env-probe @ file:") for line in frozen.splitlines())])
        return dict(python=sys.version.split()[0],uv=version,owned_wheel_sha256=sha256(wheel.read_bytes()).hexdigest(),cases=cases)


if __name__ == "__main__":
    print(json.dumps(exercise(Path(sys.argv[1]).resolve())))
本例需在 Windows CPython 3.12.14、uv 0.10.8、python-dotenv 1.2.4 与隔离开发工具。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows CPython 3.12.14、uv 0.10.8、python-dotenv 1.2.4 与隔离开发工具。

入口文件:projects/ai-agent-python-setup/env_lab.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 env_lab.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows CPython 3.12.14、uv 0.10.8、python-dotenv 1.2.4 与隔离开发工具。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:AI Agent(智能体)

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

下载课程关联工程包:AI Agent(智能体)

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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