python-uv
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePython UV Project Management
Python UV 项目管理
Provides workflows and best practices for managing Python projects using uv — Astral's fast Python package and project manager.
本文提供使用uv(Astral推出的快速Python包与项目管理器)管理Python项目的工作流及最佳实践。
Project Initialization
项目初始化
Create a new project with :
uv initbash
undefined使用创建新项目:
uv initbash
undefinedNamed project in new directory
在新目录中创建命名项目
uv init my-project
cd my-project
uv init my-project
cd my-project
Initialize in current directory
在当前目录初始化
uv init
Generated structure:
my-project/
├── .gitignore
├── .python-version
├── README.md
├── main.py
└── pyproject.toml
After the first `uv run`, `uv sync`, or `uv lock`, uv creates:
my-project/
├── .venv/
├── .python-version
├── README.md
├── main.py
├── pyproject.toml
└── uv.lock
Run the project immediately after init:
```bash
uv run main.pyuv auto-creates and syncs the virtual environment on every invocation.
uv runuv init
生成的目录结构:
my-project/
├── .gitignore
├── .python-version
├── README.md
├── main.py
└── pyproject.toml
首次执行`uv run`、`uv sync`或`uv lock`后,uv会创建以下内容:
my-project/
├── .venv/
├── .python-version
├── README.md
├── main.py
├── pyproject.toml
└── uv.lock
初始化后立即运行项目:
```bash
uv run main.py每次调用时,uv都会自动创建并同步虚拟环境。
uv runCore File Roles
核心文件作用
| File | Purpose | Commit? |
|---|---|---|
| Broad requirements, project metadata | Yes |
| Exact resolved versions, cross-platform | Yes |
| Default Python version for the project | Yes |
| Isolated virtual environment | No |
Critical rule: Commit to version control. It guarantees reproducible installs across machines and CI environments. Never edit it manually.
uv.lock| 文件 | 用途 | 是否提交到版本控制? |
|---|---|---|
| 宽泛的依赖要求、项目元数据 | 是 |
| 精确的已解析版本、跨平台兼容 | 是 |
| 项目默认Python版本 | 是 |
| 隔离的虚拟环境 | 否 |
关键规则:将提交到版本控制中。它能保证在不同机器和CI环境中实现可复现的安装。切勿手动编辑该文件。
uv.lockManaging Dependencies
依赖管理
Runtime Dependencies
运行时依赖
bash
undefinedbash
undefinedAdd with automatic version constraint
添加依赖并自动设置版本约束
uv add requests
uv add requests
Add with explicit version constraint
添加依赖并指定明确的版本约束
uv add 'requests>=2.31.0'
uv add 'requests>=2.31.0'
Add with extras
添加包含额外功能的依赖
uv add 'pandas[excel,plot]'
uv add 'pandas[excel,plot]'
Add platform-specific dependency
添加特定平台的依赖
uv add "jax; sys_platform == 'linux'"
undefineduv add "jax; sys_platform == 'linux'"
undefinedDevelopment Dependencies
开发依赖
Separate dev dependencies from published requirements using dependency groups:
bash
undefined使用依赖组将开发依赖与发布依赖分离:
bash
undefinedAdd to the default dev group (not published to PyPI)
添加到默认dev组(不会发布到PyPI)
uv add --dev pytest ruff mypy
uv add --dev pytest ruff mypy
Add to named groups for fine-grained control
添加到命名组以实现精细化控制
uv add --group lint ruff
uv add --group test pytest pytest-cov
uv add --group docs mkdocs
Resulting `pyproject.toml`:
```toml
[dependency-groups]
dev = ["pytest>=8.1.1,<9"]
lint = ["ruff>=0.4.0"]
test = ["pytest", "pytest-cov"]Groups can nest to avoid duplication:
toml
[dependency-groups]
lint = ["ruff"]
test = ["pytest"]
dev = [
{include-group = "lint"},
{include-group = "test"},
]uv add --group lint ruff
uv add --group test pytest pytest-cov
uv add --group docs mkdocs
生成的`pyproject.toml`内容:
```toml
[dependency-groups]
dev = ["pytest>=8.1.1,<9"]
lint = ["ruff>=0.4.0"]
test = ["pytest", "pytest-cov"]依赖组可以嵌套以避免重复:
toml
[dependency-groups]
lint = ["ruff"]
test = ["pytest"]
dev = [
{include-group = "lint"},
{include-group = "test"},
]Removing and Upgrading
移除与升级
bash
undefinedbash
undefinedRemove a dependency
移除依赖
uv remove requests
uv remove requests
Upgrade a specific package to latest compatible version
将指定包升级到最新兼容版本
uv lock --upgrade-package requests
uv lock --upgrade-package requests
Upgrade all packages
升级所有包
uv lock --upgrade
undefineduv lock --upgrade
undefinedRunning Commands
运行命令
Always use — it ensures the environment is synced before execution:
uv runbash
undefined请始终使用——它会确保在执行前同步环境:
uv runbash
undefinedRun a Python script
运行Python脚本
uv run main.py
uv run main.py
Run a tool from the environment
运行环境中的工具
uv add flask
uv run -- flask run -p 3000
uv add flask
uv run -- flask run -p 3000
Run with a one-off extra dependency (not added to project)
使用一次性额外依赖运行(不会添加到项目中)
uv run --with rich python -c "import rich; rich.print('[bold]Hello[/bold]')"
uv run --with rich python -c "import rich; rich.print('[bold]Hello[/bold]')"
Run only specific dependency groups
仅运行特定依赖组
uv run --no-default-groups --group test pytest
Alternatively, sync and activate manually when needed (e.g., interactive shells):
```bashuv run --no-default-groups --group test pytest
在需要时(如交互式shell),也可以手动同步并激活环境:
```bashmacOS/Linux
macOS/Linux
uv sync
source .venv/bin/activate
uv sync
source .venv/bin/activate
Windows
Windows
uv sync
.venv\Scripts\activate
**Do not** use `uv pip install` for project dependencies — use `uv add` instead. Direct pip manipulation bypasses the lockfile and breaks reproducibility.uv sync
.venv\Scripts\activate
**请勿**使用`uv pip install`安装项目依赖——请改用`uv add`。直接使用pip操作会绕过锁定文件,破坏可复现性。Dependency Sources
依赖源
Override where packages are fetched from during development using :
tool.uv.sourcesbash
undefined开发期间可使用覆盖包的获取来源:
tool.uv.sourcesbash
undefinedFrom a local path (editable)
从本地路径安装(可编辑)
uv add --editable ../my-lib
uv add --editable ../my-lib
From a Git repository
从Git仓库安装
uv add git+https://github.com/encode/httpx
uv add git+https://github.com/encode/httpx
Pin to a specific Git tag
固定到特定Git标签
uv add git+https://github.com/encode/httpx --tag 0.27.0
uv add git+https://github.com/encode/httpx --tag 0.27.0
From a custom index
从自定义索引安装
uv add torch --index pytorch=https://download.pytorch.org/whl/cpu
Sources are a uv-only development feature. Use `--no-sources` to validate that published metadata is self-contained:
```bash
uv lock --no-sources
uv build --no-sourcesuv add torch --index pytorch=https://download.pytorch.org/whl/cpu
依赖源是uv独有的开发特性。使用`--no-sources`可验证发布元数据是否独立完整:
```bash
uv lock --no-sources
uv build --no-sourcesSyncing and Locking
同步与锁定
bash
undefinedbash
undefinedSync environment to lockfile (installs missing, removes extra)
将环境与锁定文件同步(安装缺失依赖,移除多余依赖)
uv sync
uv sync
Sync including all dependency groups
同步所有依赖组
uv sync --all-groups
uv sync --all-groups
Sync only specific groups
仅同步特定组
uv sync --group test
uv sync --group test
Regenerate lockfile without syncing
重新生成锁定文件但不同步环境
uv lock
uv lock
Check if lockfile is up-to-date (for CI)
检查锁定文件是否为最新版本(用于CI)
uv lock --check
undefineduv lock --check
undefinedBuilding and Viewing Version
构建与查看版本
bash
undefinedbash
undefinedBuild source distribution and wheel
构建源码分发包与wheel包
uv build
uv build
Check built artifacts
查看构建产物
ls dist/
ls dist/
my-project-0.1.0-py3-none-any.whl
my-project-0.1.0-py3-none-any.whl
my-project-0.1.0.tar.gz
my-project-0.1.0.tar.gz
View current package version
查看当前包版本
uv version
uv version --short # 0.1.0 only
uv version --output-format json
undefineduv version
uv version --short # 仅显示0.1.0
uv version --output-format json
undefinedBest Practices
最佳实践
Lockfile hygiene
- Commit ; never edit it manually
uv.lock - Run in CI to detect uncommitted lockfile drift
uv lock --check - Use for targeted upgrades, not
uv lock --upgrade-package <name>carelessly--upgrade
Dependency discipline
- Use /
--devfor all non-runtime dependencies (linters, formatters, test runners, type checkers)--group - Never use directly in a project — always
uv pip installuv add - Set in
requires-pythonto lock down supported versionspyproject.toml
Environment hygiene
- Never commit ; the generated
.venv/excludes it by default.gitignore - Use rather than activating the venv manually in scripts and CI
uv run - For one-off tools, prefer over installing into the project environment
uvx <tool>
Publishing safety
- Run before publishing to validate published metadata is correct without
uv build --no-sourcesoverridestool.uv.sources
pyproject.toml example (library pattern):
toml
[project]
name = "my-lib"
version = "0.1.0"
description = "A short description"
readme = "README.md"
requires-python = ">=3.11"
dependencies = [
"httpx>=0.27.0",
]
[project.optional-dependencies]
network = ["aiohttp>=3.9"]
[dependency-groups]
dev = [
{include-group = "lint"},
{include-group = "test"},
]
lint = ["ruff>=0.4.0", "mypy>=1.10"]
test = ["pytest>=8.0", "pytest-cov>=5.0"]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"锁定文件维护
- 提交到版本控制;切勿手动编辑
uv.lock - 在CI中运行以检测未提交的锁定文件变更
uv lock --check - 针对特定包升级请使用,不要随意使用
uv lock --upgrade-package <name>--upgrade
依赖管理规范
- 所有非运行时依赖(代码检查器、格式化工具、测试运行器、类型检查器)均使用/
--dev添加--group - 切勿在项目中直接使用——请始终使用
uv pip installuv add - 在中设置
pyproject.toml以锁定支持的Python版本requires-python
环境维护
- 请勿提交;生成的
.venv/默认会排除该目录.gitignore - 在脚本和CI中请使用,而非手动激活虚拟环境
uv run - 对于一次性工具,优先使用而非安装到项目环境中
uvx <tool>
发布安全
- 发布前运行以验证发布元数据在没有
uv build --no-sources覆盖的情况下是否正确tool.uv.sources
pyproject.toml示例(库模式):
toml
[project]
name = "my-lib"
version = "0.1.0"
description = "A short description"
readme = "README.md"
requires-python = ">=3.11"
dependencies = [
"httpx>=0.27.0",
]
[project.optional-dependencies]
network = ["aiohttp>=3.9"]
[dependency-groups]
dev = [
{include-group = "lint"},
{include-group = "test"},
]
lint = ["ruff>=0.4.0", "mypy>=1.10"]
test = ["pytest>=8.0", "pytest-cov>=5.0"]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"Quick Reference
快速参考
| Task | Command |
|---|---|
| Create project | |
| Run script | |
| Add dependency | |
| Add dev dependency | |
| Add to named group | |
| Remove dependency | |
| Upgrade package | |
| Sync environment | |
| Rebuild lockfile | |
| Build distributions | |
| Check version | |
| Run tool one-off | |
| Simulate no sources | |
| 任务 | 命令 |
|---|---|
| 创建项目 | |
| 运行脚本 | |
| 添加依赖 | |
| 添加开发依赖 | |
| 添加到命名组 | |
| 移除依赖 | |
| 升级包 | |
| 同步环境 | |
| 重建锁定文件 | |
| 构建分发包 | |
| 查看版本 | |
| 一次性运行工具 | |
| 模拟无依赖源 | |
Additional Resources
其他资源
Reference Files
参考文档
For detailed information, consult:
- — Advanced dependency configuration: optional extras, platform markers, multiple sources, editable installs, and dependency specifier syntax
references/dependency-management.md - — Deep dive on
references/project-structure.md,pyproject.toml,uv.lock, workspace layout, and configuration options.python-version
如需详细信息,请查阅:
- —— 高级依赖配置:可选额外功能、平台标记、多源、可编辑安装及依赖指定语法
references/dependency-management.md - —— 深入讲解
references/project-structure.md、pyproject.toml、uv.lock、工作区布局及配置选项.python-version