python-uv

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Python 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 init
:
bash
undefined
使用
uv init
创建新项目:
bash
undefined

Named 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.py
uv auto-creates and syncs the virtual environment on every
uv run
invocation.
uv 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 run
时,uv都会自动创建并同步虚拟环境。

Core File Roles

核心文件作用

FilePurposeCommit?
pyproject.toml
Broad requirements, project metadataYes
uv.lock
Exact resolved versions, cross-platformYes
.python-version
Default Python version for the projectYes
.venv/
Isolated virtual environmentNo
Critical rule: Commit
uv.lock
to version control. It guarantees reproducible installs across machines and CI environments. Never edit it manually.
文件用途是否提交到版本控制?
pyproject.toml
宽泛的依赖要求、项目元数据
uv.lock
精确的已解析版本、跨平台兼容
.python-version
项目默认Python版本
.venv/
隔离的虚拟环境
关键规则:将
uv.lock
提交到版本控制中。它能保证在不同机器和CI环境中实现可复现的安装。切勿手动编辑该文件。

Managing Dependencies

依赖管理

Runtime Dependencies

运行时依赖

bash
undefined
bash
undefined

Add 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'"
undefined
uv add "jax; sys_platform == 'linux'"
undefined

Development Dependencies

开发依赖

Separate dev dependencies from published requirements using dependency groups:
bash
undefined
使用依赖组将开发依赖与发布依赖分离:
bash
undefined

Add 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
undefined
bash
undefined

Remove 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
undefined
uv lock --upgrade
undefined

Running Commands

运行命令

Always use
uv run
— it ensures the environment is synced before execution:
bash
undefined
请始终使用
uv run
——它会确保在执行前同步环境:
bash
undefined

Run 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):

```bash
uv run --no-default-groups --group test pytest

在需要时(如交互式shell),也可以手动同步并激活环境:

```bash

macOS/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.sources
:
bash
undefined
开发期间可使用
tool.uv.sources
覆盖包的获取来源:
bash
undefined

From a local path (editable)

从本地路径安装(可编辑)

uv add --editable ../my-lib
uv add --editable ../my-lib

From a Git repository

从Git仓库安装

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-sources
uv add torch --index pytorch=https://download.pytorch.org/whl/cpu

依赖源是uv独有的开发特性。使用`--no-sources`可验证发布元数据是否独立完整:

```bash
uv lock --no-sources
uv build --no-sources

Syncing and Locking

同步与锁定

bash
undefined
bash
undefined

Sync 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
undefined
uv lock --check
undefined

Building and Viewing Version

构建与查看版本

bash
undefined
bash
undefined

Build 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
undefined
uv version uv version --short # 仅显示0.1.0 uv version --output-format json
undefined

Best Practices

最佳实践

Lockfile hygiene
  • Commit
    uv.lock
    ; never edit it manually
  • Run
    uv lock --check
    in CI to detect uncommitted lockfile drift
  • Use
    uv lock --upgrade-package <name>
    for targeted upgrades, not
    --upgrade
    carelessly
Dependency discipline
  • Use
    --dev
    /
    --group
    for all non-runtime dependencies (linters, formatters, test runners, type checkers)
  • Never use
    uv pip install
    directly in a project — always
    uv add
  • Set
    requires-python
    in
    pyproject.toml
    to lock down supported versions
Environment hygiene
  • Never commit
    .venv/
    ; the generated
    .gitignore
    excludes it by default
  • Use
    uv run
    rather than activating the venv manually in scripts and CI
  • For one-off tools, prefer
    uvx <tool>
    over installing into the project environment
Publishing safety
  • Run
    uv build --no-sources
    before publishing to validate published metadata is correct without
    tool.uv.sources
    overrides
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 install
    ——请始终使用
    uv add
  • pyproject.toml
    中设置
    requires-python
    以锁定支持的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

快速参考

TaskCommand
Create project
uv init <name>
Run script
uv run <file.py>
Add dependency
uv add <package>
Add dev dependency
uv add --dev <package>
Add to named group
uv add --group <group> <package>
Remove dependency
uv remove <package>
Upgrade package
uv lock --upgrade-package <name>
Sync environment
uv sync
Rebuild lockfile
uv lock
Build distributions
uv build
Check version
uv version
Run tool one-off
uv run --with <pkg> python ...
Simulate no sources
uv lock --no-sources
任务命令
创建项目
uv init <name>
运行脚本
uv run <file.py>
添加依赖
uv add <package>
添加开发依赖
uv add --dev <package>
添加到命名组
uv add --group <group> <package>
移除依赖
uv remove <package>
升级包
uv lock --upgrade-package <name>
同步环境
uv sync
重建锁定文件
uv lock
构建分发包
uv build
查看版本
uv version
一次性运行工具
uv run --with <pkg> python ...
模拟无依赖源
uv lock --no-sources

Additional Resources

其他资源

Reference Files

参考文档

For detailed information, consult:
  • references/dependency-management.md
    — Advanced dependency configuration: optional extras, platform markers, multiple sources, editable installs, and dependency specifier syntax
  • references/project-structure.md
    — Deep dive on
    pyproject.toml
    ,
    uv.lock
    ,
    .python-version
    , workspace layout, and configuration options
如需详细信息,请查阅:
  • references/dependency-management.md
    —— 高级依赖配置:可选额外功能、平台标记、多源、可编辑安装及依赖指定语法
  • references/project-structure.md
    —— 深入讲解
    pyproject.toml
    uv.lock
    .python-version
    、工作区布局及配置选项