Published on

Guid to using uv manage python version and package

Authors
  • avatar
    Name
    Azimuth
    Twitter

简述

An extremely fast Python package and project manager, written in Rust.

  • A single tool to replace pip, pip-tools, pipx, poetry, pyenv, twine, virtualenv, and more.
  • 10-100x faster than pip.
  • Provides comprehensive project management, with a universal lockfile.
  • Runs scripts, with support for inline dependency metadata.
  • Installs and manages Python versions.
  • Runs and installs tools published as Python packages.
  • Includes a pip-compatible interface for a performance boost with a familiar CLI.
  • Supports Cargo-style workspaces for scalable projects.
  • Disk-space efficient, with a global cache for dependency deduplication.
  • Installable without Rust or Python via curl or pip.
  • Supports macOS, Linux, and Windows.

特性

  • 单文件二进制: 它是一个用 Rust 写的单文件程序,不依赖系统已有的 Python。

  • Universal Lockfile: 它的 uv.lock 是跨平台的,在 Windows 生成的锁文件,在 Linux 上也能完美运行。

  • 零配置缓存: 如果你在项目 A 安装了某包,项目 B 再安装时会直接利用缓存,速度近乎瞬间。

使用

1、官方文档

官方文档地址:https://docs.astral.sh/uv/

2、常用命令

项目管理

uv init my-project # 初始化一个新项目
cd my-project
uv add fastapi # 自动创建虚拟环境并添加依赖
uv add --dev pytest # 添加开发环境依赖
uv run main.py # 在虚拟环境中运行脚本(无需手动 activate)
uv sync # 确保环境与 lock 文件完全一致

Python版本管理

不再需要安装 pyenv,uv 直接就能管理 Python 版本:

uv python install 3.12    # 下载并安装指定的 Python 版本
uv python list            # 查看已安装和可用的 Python 版本
uv python pin 3.11        # 为当前项目固定 Python 版本

替代 Pip 的用法

uv pip install requests   # 极其快速地安装包
uv pip freeze > requirements.txt

运行工具(替代 pipx)

想临时运行一个工具(如 ruff 或 httpie)而不安装到当前项目:

uvx ruff check .          # 下载并运行 ruff

案例

使用uv 搭建一个现代化的 FastAPI 项目环境

Install uv

# Windows (PowerShell)
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

# macOS / Linux
curl -LsSf https://astral.sh/uv/install.sh | sh

init

创建一个新目录并进入,然后让 uv 初始化项目骨架

uv init fastapi-demo
cd fastapi-demo

add dependency

让 uv 帮你安装 FastAPI 和高性能服务器:会自动为你创建一个隔离的虚拟环境(.venv),它会极速下载并安装包,会生成一个 uv.lock 文件,确保别人运行你的项目时依赖完全一致。

uv add fastapi uvicorn

添加代码

改 hello.py(这是 uv init 默认生成的文件)或者新建一个 main.py:


# main.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def home():
    return {"message": "Hello from FastAPI + uv!"}

@app.get("/status")
def status():
    return {"status": "Running", "managed_by": "uv"}

运行项目

  • 使用 FastAPI 官方脚手架
uv run fastapi dev main.py
  • 直接调用 Uvicorn
uv run uvicorn main:app --reload

案例总结

  • 无需手动创建环境:不用再敲 python -m venv venv。

  • 无需激活环境:uv run 会自动在当前目录的虚拟环境下执行命令,你不用管 source activate。

  • 秒级安装:如果你以后要在第二个项目装 FastAPI,uv 会直接从缓存里拿,安装时间接近 0 秒。