来源:我们测试了 5 种虚拟环境,结果证明:最强的还是 2008 年的 venv。基于其内容由 Gemini 稍加整理和发挥。下一次我就这么干。

使用 uv

创建项目

# 创建工程基础手脚架,比如 git、project.toml...
uv init my_project && cd my_project

# 指定某个特定版本(可选)
uv python pin 3.12

# 添加依赖。移除用 remove。添加依赖会自动生成 .venv 虚拟环境目录
uv add requests pandas           # 生产依赖
uv add --dev pyinstaller         # 开发依赖,仅用于打包

:亲测指定的版本和当前 uv 安装的版本不一致时会报错,要手动修改一下 project.toml.python-version。选不同的版本可能会影响依赖安装,项目开发中修改过后需要重新更新一下依赖。

开发

除了使用常规的 .venv/bin/activate 激活虚拟环境后运行命令,也可以直接加上 uv run

  • 运行脚本: uv run main.py

  • 交互式 Shell: uv run python

更新依赖除了上面的 addremove,也可修改 pyproject.toml。修改后记得运行 uv sync

打包

  • 单文件:
uv run pyinstaller --onefile --windowed main.py
  • 目录:
uv run pyinstaller --onedir --windowed main.py

使用 pip-tools

  1. 针对 Linux 系统的整合流程
# 1. 创建虚拟环境并自动更新基础工具 (pip, setuptools)
python3 -m venv .venv --upgrade-deps

# 2. 激活环境
source .venv/bin/activate

# 3. 安装依赖管理工具
pip install pip-tools

# 4. 初始化依赖清单 (如果文件不存在)
# 你可以在 requirements.in 中写入你需要的直接依赖,例如: requests, pandas
touch requirements.in

# 5. 编译依赖(生成带哈希值的锁定文件 requirements.txt)
pip-compile --generate-hashes --strip-extras --output-file=requirements.txt requirements.in

# 6. 同步环境(根据锁定文件安装/删除包,确保本地环境与锁定文件完全一致)
pip-sync
  1. 针对 Windows 系统的整合流程
# 1. 创建虚拟环境
python -m venv .venv --upgrade-deps

# 2. 激活环境
.venv\Scripts\activate

# 3. 安装工具
pip install pip-tools

# 4. 初始化清单 (PowerShell 语法)
if (!(Test-Path requirements.in)) { New-Item requirements.in }

# 5. 编译锁定文件
pip-compile --generate-hashes --strip-extras --output-file=requirements.txt requirements.in

# 6. 执行同步
pip-sync

警示 如果手动用 pip install 安装了一个临时工具,但没有把它写进 requirements.in 并重新编译,那么下一次运行 pip-sync 时,这个工具会被直接删掉。