本文将介绍如何在国内网络环境中使用 UV 快速构建深度学习开发环境,包括 UV 的安装、Python 下载加速、项目初始化、依赖管理与运行方式。
一、安装 UV 工具
在国外网络环境下可以直接通过官方脚本安装:
sh
curl -LsSf https://astral.sh/uv/install.sh | sh
在国内环境中建议使用更稳定的方式安装:
1. Ubuntu
Ubuntu 用户可通过 Snap 直接安装国内镜像版本:
sh
sudo snap install astral-uv --classic
2. macOS
macOS 用户可使用 Homebrew,在配置好国内镜像源后执行:
sh
brew install uv
3. 通过 pip 安装
若系统已有 pip,可以从国内 PyPI 镜像安装:
sh
pip install uv -i https://pypi.tuna.tsinghua.edu.cn/simple
二、使用 UV 安装 Python
由于默认下载源 Github 经常受到地域限制,UV 支持通过环境变量指定国内镜像以加速 Python 下载。
1. 设置环境变量
Windows:
cmd
set UV_PYTHON_INSTALL_MIRROR=https://registry.npmmirror.com/-/binary/python-build-standalone
Unix / Linux / macOS:
sh
export UV_PYTHON_INSTALL_MIRROR=https://registry.npmmirror.com/-/binary/python-build-standalone
2. 安装指定版本 Python
例如安装 Python 3.12:
sh
uv python install 3.12
UV 将自动从镜像站点下载并安装对应的 Python 版本,适合国内环境使用。
三、初始化项目环境
1. 创建配置文件
进入你的工作目录,例如 deeplearn/,然后执行:
sh
uv init --bare
该命令会创建由pyproject.toml定义的最小化 Python 项目结构,包括:
toml
[project]
name = "deeplearn"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = []
2. 添加默认 PyPI 镜像源
为进一步提升依赖安装速度,可在 pyproject.toml 中追加:
toml
[[tool.uv.index]]
url = "https://pypi.tuna.tsinghua.edu.cn/simple"
3. 配置 PyTorch 官方镜像
toml
[[tool.uv.index]]
name = "pytorch-cu130"
url = "https://download.pytorch.org/whl/cu130"
explicit = true
[tool.uv.sources]
torch = { index = "pytorch-cu130" }
torchvision = { index = "pytorch-cu130" }
这样即可确保 PyTorch 和 TorchVision 从正确的 CUDA 对应版本安装。
四、使用 UV 进行包管理
1. 安装依赖
UV 使用 uv add 安装包,并自动写入 pyproject.toml:
sh
uv add torch torchvision
2. 删除依赖
sh
uv remove 包名
3. 同步环境
当你从其他机器复制了项目,需要恢复环境时:
sh
uv sync
五、运行程序
使用 uv run 可在虚拟环境中运行 Python 程序,无需手动激活环境:
sh
uv run main.py
UV 会自动创建 .venv 虚拟环境,若需要手动激活 .venv:
-
Unix / Linux / macOS:
shsource .venv/bin/activate -
Windows:
powershell.venv\Scripts\activate