package-managing

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

uv Package and Project Manager

uv 包与项目管理器

Overview

概述

uv is a fast Python package and project manager written in Rust. It serves as a single tool replacing pip, pip-tools, pipx, pyenv, virtualenv, and poetry. Use uv for dependency resolution, virtual environment management, Python version management, and project scaffolding.
Key characteristics:
  • 10-100x faster than pip for dependency resolution and installation
  • Built-in virtual environment management (automatic
    .venv
    creation)
  • Lockfile support for reproducible builds
  • Python version management without pyenv
  • Cross-platform with no Python prerequisite for installation
uv是一款基于Rust开发的快速Python包与项目管理器。它是一款一站式工具,可替代pip、pip-tools、pipx、pyenv、virtualenv和poetry。你可以使用uv进行依赖解析、虚拟环境管理、Python版本管理以及项目脚手架搭建。
核心特性:
  • 依赖解析与安装速度比pip快10-100倍
  • 内置虚拟环境管理(自动创建
    .venv
  • 支持锁文件,实现可复现的构建
  • 无需pyenv即可管理Python版本
  • 跨平台,安装无需预先安装Python

Project Initialization

项目初始化

Creating a New Project

创建新项目

Use
uv init
to scaffold a new Python project.
bash
undefined
使用
uv init
搭建新的Python项目。
bash
undefined

Create a project in a new directory

在新目录中创建项目

uv init my-project
uv init my-project

Initialize in the current directory

在当前目录初始化项目

uv init
uv init

Create an application project (default, no build system)

创建应用项目(默认,无构建系统)

uv init --app my-app
uv init --app my-app

Create a library project (includes build system for publishing)

创建库项目(包含用于发布的构建系统)

uv init --lib my-lib
uv init --lib my-lib

Specify minimum Python version at init time

初始化时指定最低Python版本

uv init --python ">=3.12" my-project
undefined
uv init --python ">=3.12" my-project
undefined

Project Layout

项目结构

An application project (
--app
) produces:
my-app/
  .python-version
  pyproject.toml
  README.md
  main.py
A library project (
--lib
) produces:
my-lib/
  .python-version
  pyproject.toml
  README.md
  src/
    my_lib/
      __init__.py
      py.typed
For FastAPI services, prefer
--app
and reorganize into a
src/
layout manually if needed.
应用项目(
--app
)的结构如下:
my-app/
  .python-version
  pyproject.toml
  README.md
  main.py
库项目(
--lib
)的结构如下:
my-lib/
  .python-version
  pyproject.toml
  README.md
  src/
    my_lib/
      __init__.py
      py.typed
对于FastAPI服务,建议使用
--app
创建,若需要可手动调整为
src/
结构。

pyproject.toml Structure

pyproject.toml 结构

The
pyproject.toml
file is the single source of truth for project metadata, dependencies, and tool configuration.
pyproject.toml
文件是项目元数据、依赖和工具配置的唯一来源。

Core Sections

核心章节

toml
[project]
name = "my-project"
version = "0.1.0"
description = "A short project description"
requires-python = ">=3.12"
readme = "README.md"
license = { text = "MIT" }
dependencies = [
    "fastapi>=0.115",
    "uvicorn[standard]>=0.34",
]

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
toml
[project]
name = "my-project"
version = "0.1.0"
description = "简短的项目描述"
requires-python = ">=3.12"
readme = "README.md"
license = { text = "MIT" }
dependencies = [
    "fastapi>=0.115",
    "uvicorn[standard]>=0.34",
]

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

Dependency Groups

依赖组

Use
[dependency-groups]
to organize development and optional dependency sets.
toml
[dependency-groups]
dev = [
    "pytest>=8.0",
    "pytest-asyncio>=0.25",
    "ruff>=0.9",
    "mypy>=1.14",
]
docs = [
    "mkdocs>=1.6",
    "mkdocs-material>=9.5",
]
使用
[dependency-groups]
组织开发依赖和可选依赖集合。
toml
[dependency-groups]
dev = [
    "pytest>=8.0",
    "pytest-asyncio>=0.25",
    "ruff>=0.9",
    "mypy>=1.14",
]
docs = [
    "mkdocs>=1.6",
    "mkdocs-material>=9.5",
]

uv-Specific Configuration

uv专属配置

The
[tool.uv]
section controls uv behavior.
toml
[tool.uv]
[tool.uv]
章节用于控制uv的行为。
toml
[tool.uv]

Override dependency resolution for specific packages

覆盖特定包的依赖解析

override-dependencies = [ "numpy>=2.0", ]
override-dependencies = [ "numpy>=2.0", ]

Constrain transitive dependency versions

限制传递依赖的版本

constraint-dependencies = [ "grpcio<1.70", ]
constraint-dependencies = [ "grpcio<1.70", ]

Default groups to install on uv sync

uv sync时默认安装的依赖组

default-groups = ["dev"]

See `assets/pyproject-template.toml` for a production-ready FastAPI project template.
default-groups = ["dev"]

可查看`assets/pyproject-template.toml`获取生产就绪的FastAPI项目模板。

Dependency Management

依赖管理

Adding Dependencies

添加依赖

bash
undefined
bash
undefined

Add a production dependency

添加生产依赖

uv add fastapi
uv add fastapi

Add with version constraint

添加带版本约束的依赖

uv add "pydantic>=2.0,<3.0"
uv add "pydantic>=2.0,<3.0"

Add multiple packages at once

同时添加多个包

uv add fastapi uvicorn pydantic-settings
uv add fastapi uvicorn pydantic-settings

Add a development dependency

添加开发依赖

uv add --dev pytest ruff mypy
uv add --dev pytest ruff mypy

Add to a named dependency group

添加到指定依赖组

uv add --group docs mkdocs mkdocs-material
uv add --group docs mkdocs mkdocs-material

Add with extras

添加包含额外功能的依赖

uv add "uvicorn[standard]"
uv add "uvicorn[standard]"

Add a git dependency

添加Git依赖

uv add "my-package @ git+https://github.com/org/repo.git@main"
uv add "my-package @ git+https://github.com/org/repo.git@main"

Add a local path dependency (editable)

添加本地路径依赖(可编辑模式)

uv add --editable "../shared-lib"
undefined
uv add --editable "../shared-lib"
undefined

Removing Dependencies

移除依赖

bash
undefined
bash
undefined

Remove a production dependency

移除生产依赖

uv remove httpx
uv remove httpx

Remove a dev dependency

移除开发依赖

uv remove --dev mypy
uv remove --dev mypy

Remove from a named group

从指定组移除依赖

uv remove --group docs mkdocs
undefined
uv remove --group docs mkdocs
undefined

Version Constraints

版本约束

uv follows PEP 440 version specifiers:
SpecifierMeaning
>=1.0
Version 1.0 or higher
>=1.0,<2.0
At least 1.0, below 2.0
~=1.4
Compatible release (>=1.4, <2.0)
==1.4.*
Any patch of 1.4
>=1.0; python_version>="3.12"
Environment marker
uv遵循PEP 440版本规范:
规范符含义
>=1.0
版本1.0或更高
>=1.0,<2.0
至少1.0,低于2.0
~=1.4
兼容版本(>=1.4,<2.0)
==1.4.*
1.4的任何补丁版本
>=1.0; python_version>="3.12"
环境标记

Lock File

锁文件

Generating the Lock File

生成锁文件

The
uv.lock
file pins every direct and transitive dependency to an exact version for reproducible installs.
bash
undefined
uv.lock
文件会将所有直接和传递依赖固定到精确版本,以实现可复现的安装。
bash
undefined

Generate or update the lock file

生成或更新锁文件

uv lock
uv lock

Update a single package in the lock file

更新锁文件中的单个包

uv lock --upgrade-package fastapi
uv lock --upgrade-package fastapi

Upgrade all packages to latest compatible versions

将所有包升级到最新兼容版本

uv lock --upgrade
undefined
uv lock --upgrade
undefined

When to Lock vs Sync

何时使用Lock与Sync

  • Run
    uv lock
    after editing
    pyproject.toml
    manually or to refresh resolved versions.
  • Run
    uv sync
    to install dependencies from the lock file into the virtual environment.
  • uv add
    and
    uv remove
    automatically update both
    pyproject.toml
    and
    uv.lock
    .
Always commit
uv.lock
to version control for applications. For libraries, committing the lock file is optional but recommended for CI reproducibility.
  • 手动编辑
    pyproject.toml
    后,或需要刷新解析版本时,运行
    uv lock
  • 运行
    uv sync
    将锁文件中的依赖安装到虚拟环境中。
  • uv add
    uv remove
    会自动更新
    pyproject.toml
    uv.lock
对于应用程序,务必将
uv.lock
提交到版本控制。对于库,提交锁文件是可选的,但为了CI的可复现性,建议提交。

Syncing the Environment

同步环境

uv sync
installs the exact versions from
uv.lock
into the project virtual environment.
bash
undefined
uv sync
会将
uv.lock
中的精确版本安装到项目虚拟环境中。
bash
undefined

Sync all dependencies (creates .venv if missing)

同步所有依赖(若缺少则创建.venv)

uv sync
uv sync

Sync without updating the lock file (CI-friendly, fails if lock is stale)

同步时不更新锁文件(适合CI,若锁文件过时则失败)

uv sync --frozen
uv sync --frozen

Sync without dev dependencies (production builds)

同步时不包含开发依赖(生产构建)

uv sync --no-dev
uv sync --no-dev

Sync including a specific extra group

同步包含指定额外组

uv sync --group docs
uv sync --group docs

Sync all groups

同步所有组

uv sync --all-groups
uv sync --all-groups

Reinstall all packages from scratch

重新安装所有包

uv sync --reinstall

In CI pipelines, always use `uv sync --frozen` to ensure the lock file is up to date and avoid unexpected resolution changes.
uv sync --reinstall

在CI流水线中,始终使用`uv sync --frozen`以确保锁文件是最新的,避免意外的解析变化。

Running Commands

运行命令

Use
uv run
to execute commands within the project virtual environment without manually activating it.
bash
undefined
使用
uv run
在项目虚拟环境中执行命令,无需手动激活环境。
bash
undefined

Run a Python script

运行Python脚本

uv run python main.py
uv run python main.py

Run pytest

运行pytest

uv run pytest tests/ -v
uv run pytest tests/ -v

Run a FastAPI dev server

运行FastAPI开发服务器

uv run uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
uv run uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

Run FastAPI CLI dev server

运行FastAPI CLI开发服务器

uv run fastapi dev app/main.py
uv run fastapi dev app/main.py

Run ruff linter

运行ruff代码检查器

uv run ruff check .
uv run ruff check .

Run mypy type checker

运行mypy类型检查器

uv run mypy src/
uv run mypy src/

Run an arbitrary module

运行任意模块

uv run python -m my_module

`uv run` automatically creates the virtual environment and syncs dependencies if needed before executing the command.
uv run python -m my_module

`uv run`会在执行命令前自动创建虚拟环境并同步依赖(若需要)。

Virtual Environments

虚拟环境

Automatic Management

自动管理

uv creates and manages a
.venv
directory in the project root automatically. There is no need to manually create or activate virtual environments for most workflows --
uv run
,
uv sync
, and
uv add
all handle this.
uv会在项目根目录自动创建并管理
.venv
目录。大多数工作流无需手动创建或激活虚拟环境——
uv run
uv sync
uv add
都会处理这些操作。

Manual Creation

手动创建

bash
undefined
bash
undefined

Create a venv with the default Python

使用默认Python创建虚拟环境

uv venv
uv venv

Create a venv with a specific Python version

使用指定Python版本创建虚拟环境

uv venv --python 3.12
uv venv --python 3.12

Create a venv at a custom path

在自定义路径创建虚拟环境

uv venv /path/to/venv
uv venv /path/to/venv

Activate manually (rarely needed with uv run)

手动激活(使用uv run时几乎不需要)

source .venv/bin/activate # macOS/Linux .venv\Scripts\activate # Windows
undefined
source .venv/bin/activate # macOS/Linux .venv\Scripts\activate # Windows
undefined

IDE Integration

IDE集成

Point IDE Python interpreters to
.venv/bin/python
(macOS/Linux) or
.venv\Scripts\python.exe
(Windows) to get autocomplete and type checking aligned with project dependencies.
将IDE的Python解释器指向
.venv/bin/python
(macOS/Linux)或
.venv\Scripts\python.exe
(Windows),使自动补全和类型检查与项目依赖保持一致。

Python Version Management

Python版本管理

uv can install and manage Python versions directly, replacing pyenv.
bash
undefined
uv可以直接安装和管理Python版本,替代pyenv。
bash
undefined

Install a specific Python version

安装指定Python版本

uv python install 3.12
uv python install 3.12

Install multiple versions

安装多个版本

uv python install 3.11 3.12 3.13
uv python install 3.11 3.12 3.13

Pin the project to a specific version (writes .python-version)

将项目固定到指定Python版本(写入.python-version)

uv python pin 3.12
uv python pin 3.12

List available Python versions

列出可用的Python版本

uv python list
uv python list

List installed Python versions

列出已安装的Python版本

uv python list --only-installed

The `.python-version` file is read by uv automatically. Commit it to version control to ensure all contributors use the same Python version.
uv python list --only-installed

uv会自动读取`.python-version`文件。将其提交到版本控制,确保所有贡献者使用相同的Python版本。

Script Inline Dependencies

脚本内联依赖

For standalone scripts that need third-party packages, use PEP 723 inline metadata instead of creating a full project.
python
undefined
对于需要第三方包的独立脚本,使用PEP 723内联元数据,无需创建完整项目。
python
undefined

/// script

/// script

requires-python = ">=3.12"

requires-python = ">=3.12"

dependencies = [

dependencies = [

"httpx>=0.27",

"httpx>=0.27",

"rich>=13.0",

"rich>=13.0",

]

]

///

///

import httpx from rich import print
resp = httpx.get("https://api.example.com/data") print(resp.json())

Run the script directly with uv:

```bash
uv run script.py
uv resolves and installs the inline dependencies into an isolated, cached environment automatically. This is ideal for utility scripts, one-off tasks, and scripts shared outside a project context.
import httpx from rich import print
resp = httpx.get("https://api.example.com/data") print(resp.json())

直接使用uv运行脚本:

```bash
uv run script.py
uv会自动解析并将内联依赖安装到隔离的缓存环境中。这非常适合实用脚本、一次性任务以及在项目上下文之外共享的脚本。

Tool Management

工具管理

uv replaces pipx for installing and running Python CLI tools globally.
bash
undefined
uv可替代pipx,用于全局安装和运行Python CLI工具。
bash
undefined

Install a tool globally

全局安装工具

uv tool install ruff uv tool install uv-publish
uv tool install ruff uv tool install uv-publish

Run a tool without installing (ephemeral)

无需安装直接运行工具(临时)

uv tool run ruff check . uv tool run --from "huggingface-hub" huggingface-cli
uv tool run ruff check . uv tool run --from "huggingface-hub" huggingface-cli

Shorthand: uvx (alias for uv tool run)

简写:uvx(uv tool run的别名)

uvx ruff check . uvx black .
uvx ruff check . uvx black .

List installed tools

列出已安装的工具

uv tool list
uv tool list

Upgrade a tool

升级工具

uv tool upgrade ruff
uv tool upgrade ruff

Uninstall a tool

卸载工具

uv tool uninstall ruff

Prefer `uv tool run` / `uvx` for infrequent use. Prefer `uv tool install` for tools used regularly across projects.
uv tool uninstall ruff

对于不常用的工具,优先使用`uv tool run` / `uvx`。对于跨项目频繁使用的工具,优先使用`uv tool install`。

Workspace Support

工作区支持

Workspaces allow managing multiple related packages in a monorepo with a shared lock file.
工作区允许在单体仓库中管理多个相关包,并使用共享锁文件。

Root pyproject.toml

根目录pyproject.toml

toml
[tool.uv.workspace]
members = [
    "packages/*",
    "services/*",
]
toml
[tool.uv.workspace]
members = [
    "packages/*",
    "services/*",
]

Workspace Layout

工作区结构

monorepo/
  pyproject.toml          # Root workspace config
  uv.lock                 # Single shared lock file
  packages/
    shared-models/
      pyproject.toml
      src/shared_models/
    shared-utils/
      pyproject.toml
      src/shared_utils/
  services/
    api-service/
      pyproject.toml
      src/api_service/
    worker-service/
      pyproject.toml
      src/worker_service/
monorepo/
  pyproject.toml          # 根工作区配置
  uv.lock                 # 单个共享锁文件
  packages/
    shared-models/
      pyproject.toml
      src/shared_models/
    shared-utils/
      pyproject.toml
      src/shared_utils/
  services/
    api-service/
      pyproject.toml
      src/api_service/
    worker-service/
      pyproject.toml
      src/worker_service/

Inter-Package Dependencies

包间依赖

Reference workspace members as path dependencies:
toml
undefined
将工作区成员作为路径依赖引用:
toml
undefined

In services/api-service/pyproject.toml

在services/api-service/pyproject.toml中

[project] dependencies = [ "shared-models", "shared-utils", ]
[tool.uv.sources] shared-models = { workspace = true } shared-utils = { workspace = true }

Run commands scoped to a specific workspace member:

```bash
[project] dependencies = [ "shared-models", "shared-utils", ]
[tool.uv.sources] shared-models = { workspace = true } shared-utils = { workspace = true }

运行针对特定工作区成员的命令:

```bash

Sync a specific member

同步特定成员

uv sync --package api-service
uv sync --package api-service

Run tests for a specific member

运行特定成员的测试

uv run --package api-service pytest
undefined
uv run --package api-service pytest
undefined

Common Workflows

常见工作流

Starting a New FastAPI Project

启动新的FastAPI项目

bash
uv init --app my-api
cd my-api
uv add fastapi "uvicorn[standard]" pydantic-settings
uv add --dev pytest pytest-asyncio ruff mypy
uv run fastapi dev main.py
bash
uv init --app my-api
cd my-api
uv add fastapi "uvicorn[standard]" pydantic-settings
uv add --dev pytest pytest-asyncio ruff mypy
uv run fastapi dev main.py

Adding and Pinning a Dependency

添加并固定依赖

bash
uv add "sqlalchemy>=2.0,<3.0"
uv lock
uv sync
bash
uv add "sqlalchemy>=2.0,<3.0"
uv lock
uv sync

CI Pipeline

CI流水线

bash
uv sync --frozen --no-dev
uv run pytest --tb=short
uv run ruff check .
uv run mypy src/
bash
uv sync --frozen --no-dev
uv run pytest --tb=short
uv run ruff check .
uv run mypy src/

Upgrading Dependencies

升级依赖

bash
undefined
bash
undefined

Upgrade everything

升级所有依赖

uv lock --upgrade uv sync
uv lock --upgrade uv sync

Upgrade a single package

升级单个包

uv lock --upgrade-package fastapi uv sync
undefined
uv lock --upgrade-package fastapi uv sync
undefined

Cross-References

交叉引用

  • For FastAPI project setup, combine with the
    fastapi
    skill.
  • See
    assets/pyproject-template.toml
    for a complete production-ready project template.
  • 若要搭建FastAPI项目,请结合
    fastapi
    技能。
  • 完整的生产就绪项目模板可查看
    assets/pyproject-template.toml