Python 虚拟环境的创建(venv)
为每个项目选定解释器,隔离依赖,并从版本清单重建环境。
学完这一章,你能够
- 为每个项目选定解释器,隔离依赖,并从版本清单重建环境。
先确认隔离的范围
当两个项目需要同一软件包的不同版本时,为它们分别建环境。虚拟环境使用所选的基础 Python,通常有独立的安装目录。用 sys.prefix 和 sys.base_prefix 区分当前环境与基础安装。同一个基础解释器可以创建多个虚拟环境。
隔离的重点是包的查找和安装路径。本站在 CPython 3.12.14 用 --without-pip 创建两个环境:默认环境找不到 pip;另一个加上 --system-site-packages 后找到基础安装中的 pip,但自身 site-packages 仍没有 pip。两者的 sys.prefix 都指向各自环境,并与 sys.base_prefix 不同。两个子进程也都继承了自编环境变量,能读取环境目录外的本站临时文件。由此可见包路径隔离不等于文件或进程权限隔离;--without-pip 只省略本地 pip 初始化,不保证启用系统包后无法导入 pip。
本站用同一个基础 Python 建两个环境,分别安装自编包的两个离线版本。每个环境调用相同的导入语句,输出各自版本和结果。这样可以观察依赖冲突的解决方式。Django 两代依赖是这个问题的典型场景,使用时还要核对 Python 版本和框架支持周期。
选择解释器并创建目录
先用 python --version、python3 --version 或 Windows 上的 py -3.12 --version 确认所选解释器。再用该解释器运行 -m venv .venv。目标名可以自定,.venv 是常用约定。指定其它版本须先安装对应解释器。发行版可能把 venv 或 ensurepip 组件分开打包。
环境根目录有 pyvenv.cfg。Windows 下通常是 Scripts\python.exe、激活脚本与 Lib\site-packages。POSIX 系统下通常是 bin/python、激活脚本与 lib/pythonX.Y/site-packages。解释器可能是副本、启动器或符号链接。用 --without-pip 可跳过 pip 初始化,用 --system-site-packages 可放开基础安装的第三方包可见性。
激活、验证与停用
POSIX 上的 bash 或 zsh 可运行 source .venv/bin/activate。Windows CMD 用 .venv\Scripts\activate.bat,PowerShell 用 .\.venv\Scripts\Activate.ps1。若 PowerShell 策略限制脚本,仍可直接执行 .\.venv\Scripts\python.exe,无须改策略。
激活主要调整当前 Shell 的 PATH 和提示符。用 Python 打印 sys.executable 和前缀,或在 CMD 用 where.exe python,在 PowerShell 用 Get-Command python 查看实际命令。提示符和 VIRTUAL_ENV 可以提示激活状态,直接运行环境解释器时也能处于虚拟环境。
运行 deactivate 后恢复激活前的 Shell 状态。之前用的可能是另一个环境。重建或清理时先停用环境并确认要处理的绝对路径,只移除自己创建的环境目录。
安装、检查与重建依赖
用环境解释器执行 python -m pip,确保安装落在目标环境中。python -m pip install 包名==版本 可固定版本,多个包可一起列出。用 pip list 查看已装版本,用 pip show 查看指定包及安装位置。升级前确认目标,pip install --upgrade 包名 与升级 pip 自身是不同操作。
python -m pip freeze 可以导出当前已安装包的版本,python -m pip install -r requirements.txt 可按清单安装。freeze 记录的是当前安装结果,跨操作系统、解释器或软件源复现时仍需固定 Python、验证可用轮子及必要的平台条件。离线示例用 --no-index --find-links 指定本站临时轮子目录,公开镜像另需按项目设置选择。
做 Django 项目时,可在选定的环境中安装适配的 Django,使用 django-admin startproject config . 初始化当前项目,再用 python manage.py migrate 和 python manage.py runserver 处理迁移和本地开发服务。框架的这些步骤需要可用的 Django 安装和项目数据库。
迁移、空间与版本控制
虚拟环境记录了创建时的路径。本站 Windows 实测,在基础 Python 仍位于原处的条件下,把实验环境移到另一目录后,移动后的 pip.exe 因仍指向旧解释器路径而退出失败。直接运行移动后的 python.exe -m pip --version 则成功,并指向新目录中的 pip。其它入口仍可能保留旧路径。迁移项目时在目标位置重新创建环境并按清单安装,随后逐个验证命令和导入路径。磁盘占用取决于平台、复制方式和依赖。
把 .venv/、__pycache__/、*.pyc、.env 和生成的 *.egg-info/ 放入项目忽略规则时,保留 requirements.txt 或项目正式的依赖清单。IDE 中仍应确认选中正确解释器。
三个环境工具的选择条件
| 工具 | 类型 | Python 版本范围 | 如何获得 | 特点 | 使用场景 |
| venv | Python 标准库 | 自 Python 3.3 引入,使用所选基础解释器 | 通常随解释器提供,部分系统另装发行版组件 | 分隔 site-packages,支持保留或省略 pip | 已有合适 Python 的常规项目 |
| virtualenv | 第三方 Python 工具 | 创建工具与目标解释器支持随发行版变化,旧版本曾支持 Python 2 | 用符合该版本要求的 Python 执行 python -m pip install virtualenv | 有独立的解释器发现和环境初始化功能 | 项目需要这些功能或需管理特定历史版本时 |
| conda | 独立包和环境管理器 | 可用 Python 版本取决于包渠道和目标平台,Python 2 属历史情况 | 可由 Anaconda、Miniconda 等安装途径获得 | 同一环境可管理 Python 和非 Python 包 | 数据科学或含本机库的依赖环境 |
本章自编源码与运行范围
展开查看收起
"""蓝色天空网 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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
当前源码有命名范围的实际运行记录;原文全部事实、其它平台和IDE界面仍待逐项验收。
本章附件与实例包
常见错误与边界检查
- 命令、源码、当前解释器和具体平台分别核对,不能以单项运行推断整章验收。
技术规范与官方资料
练习与参考解答
查看参考解答
比较原始输出、修改后的输出及错误类型;未执行的平台和界面继续单列。