mcpField
U
uv-skill

uv-skill

github.com/julianobarbosa开发1458 次安装2 天前更新
代码仓库

关于 uv-skill

介绍 Astral 的 Python 包和项目管理工具 uv 的命令行 Skill 指南,涵盖项目配置、依赖、Python 版本、代码执行与发布。

主要功能

  1. 01项目与依赖管理
  2. 02可复现锁定文件
  3. 03Python 版本管理
  4. 04使用 uvx 运行工具
  5. 05构建和发布包

适用场景

  1. 01创建 Python 项目
  2. 02在 CI 中同步依赖
  3. 03运行带内联依赖的脚本
  4. 04从 pip 或 Poetry 迁移

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/julianobarbosa/claude-code-skills --skill uv-skill

安装后在 Claude Code 中输入/uv-skill确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
cli-commands.md
integrations.md
project-management.md
python-versions.md

详细介绍

uv 技能

由 Astral(Ruff 的创作者)开发的超快 Python 包和项目管理器。

概览

uv 是一款一体化工具,可替代:

  • pip/pip-tools - 包安装和依赖解析
  • virtualenv/venv - 虚拟环境创建
  • pyenv - Python 版本管理
  • pipx - 工具安装和执行
  • poetry/pdm - 项目和依赖管理
  • twine - 包发布

主要功能:

  • 速度比 pip 快 10–100 倍
  • 通用锁文件(uv.lock),实现可复现构建
  • 自动管理 Python 版本
  • 内置工具执行功能(uvx)
  • 支持 PEP 723 内联脚本依赖
  • 可直接替代 pip 使用

快速参考

任务命令
新建项目uv init
新建库uv init --lib
添加包uv add <pkg>
添加开发依赖uv add --dev <pkg>
移除包uv remove <pkg>
安装所有依赖uv sync
安装(CI/生产环境)uv sync --locked
运行命令uv run <cmd>
运行工具(无需安装)uvx <tool>
安装 Pythonuv python install 3.12
固定 Python 版本uv python pin 3.12
更新所有依赖uv lock --upgrade
更新单个包uv lock --upgrade-package <pkg>
显示依赖树uv tree
构建包uv build
发布到 PyPIuv publish

快速入门

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

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

# Via pip/pipx
pipx install uv
pip install uv

# Homebrew
brew install uv
Shell 补全
# Bash
echo 'eval "$(uv generate-shell-completion bash)"' >> ~/.bashrc

# Zsh
echo 'eval "$(uv generate-shell-completion zsh)"' >> ~/.zshrc

# Fish
echo 'uv generate-shell-completion fish | source' > ~/.config/fish/completions/uv.fish

基本命令

1. 启动项目
# Create new project
uv init my-project          # Application (default)
uv init --lib my-library    # Library (src layout, build backend)
uv init --app my-app        # Explicit application

# Set Python version
uv python pin 3.12          # Creates .python-version

# Install Python if needed
uv python install 3.12
2. 管理依赖
# Add packages
uv add requests flask       # Production dependencies
uv add --dev pytest ruff    # Development dependencies
uv add --group test pytest  # Specific dependency group
uv add --optional api flask # Optional extra
uv add "httpx>=0.20"        # With version constraint

# Remove packages
uv remove requests
uv remove --dev pytest

# Update packages
uv lock --upgrade                    # All packages
uv lock --upgrade-package requests   # Single package

# View dependencies
uv tree                     # Full tree
uv tree --depth 2           # Limited depth
3. 同步环境
# Install all dependencies
uv sync                     # Default (includes dev)
uv sync --locked            # CI/production (strict)
uv sync --frozen            # Don't update lockfile
uv sync --no-dev            # Exclude dev dependencies
uv sync --all-extras        # Include optional extras
4. 运行代码
# Run in project environment
uv run python script.py
uv run pytest
uv run flask run

# Run with temporary dependency
uv run --with pandas script.py

# Run tools without installing (uvx)
uvx ruff check .
uvx black --check .
uvx --from httpie http https://example.com
5. Python 版本管理
# Install Python versions
uv python install           # Latest version
uv python install 3.12      # Specific version
uv python install 3.11 3.12 3.13  # Multiple

# List versions
uv python list
uv python list --only-installed

# Pin version
uv python pin 3.12          # Project (.python-version)
uv python pin --global 3.12 # User default

# Find Python
uv python find
uv python find ">=3.11"
6. 虚拟环境
# Create (usually automatic)
uv venv                     # Creates .venv
uv venv my-env              # Custom name
uv venv --python 3.12       # Specific Python

# Activate (optional - uv run auto-detects)
source .venv/bin/activate   # macOS/Linux
.venv\Scripts\activate      # Windows
7. 全局工具
# Install tools globally
uv tool install ruff
uv tool install "ruff==0.5.0"
uv tool install --python 3.12 mypy

# Manage tools
uv tool list
uv tool upgrade ruff
uv tool upgrade --all
uv tool uninstall ruff

# Setup PATH
uv tool update-shell
带内联依赖的脚本(PEP 723)
# Initialize script with metadata
uv init --script example.py --python 3.12

# Add dependencies to script
uv add --script example.py requests rich

# Run script (dependencies auto-installed)
uv run example.py

脚本格式:

# /// script
# requires-python = ">=3.12"
# dependencies = [
#   "requests<3",
#   "rich",
# ]
# ///

import requests
from rich import print
print(requests.get("https://api.example.com").json())
兼容 pip 的接口
# Install packages (requires virtual environment)
uv pip install flask
uv pip install -r requirements.txt
uv pip install -e .         # Editable install

# Uninstall
uv pip uninstall flask

# Compile requirements
uv pip compile requirements.in -o requirements.txt

# Sync from requirements
uv pip sync requirements.txt

# Freeze environment
uv pip freeze
构建和发布
# Build distributions
uv build                    # Creates dist/ with wheel and sdist

# Publish to PyPI
uv publish                  # Requires authentication setup

# Authenticate
uv auth login pypi          # Interactive login
uv auth login pypi --token  # API token

项目结构

my-project/
├── pyproject.toml          # Project definition (required)
├── uv.lock                 # Lock file (auto-generated)
├── .venv/                  # Virtual environment (gitignored)
├── .python-version         # Python version pin (optional)
└── src/
    └── my_project/
        └── __init__.py
pyproject.toml 示例
[project]
name = "my-project"
version = "0.1.0"
description = "My awesome project"
readme = "README.md"
requires-python = ">=3.11"
dependencies = [
    "requests>=2.28",
    "click>=8.0",
]

[project.optional-dependencies]
api = ["fastapi", "uvicorn"]
dev = ["pytest", "ruff"]

[project.scripts]
my-cli = "my_project.cli:main"

[dependency-groups]
dev = ["pytest>=8", "ruff", "mypy"]
test = ["pytest-cov"]
docs = ["sphinx", "myst-parser"]

[tool.uv]
dev-dependencies = ["pytest", "ruff"]  # Alternative to dependency-groups
default-groups = ["dev"]

[tool.uv.sources]
# Git dependency
my-lib = { git = "https://github.com/user/my-lib" }
# Local path
local-pkg = { path = "./packages/local-pkg" }
# Specific index
torch = { index = "pytorch" }

[[tool.uv.index]]
name = "pytorch"
url = "https://download.pytorch.org/whl/cpu"
explicit = true

配置

配置文件

项目级(优先级最高):

  • uv.toml - 独立配置(首选)
  • pyproject.toml - [tool.uv] 部分

用户级:

  • ~/.config/uv/uv.toml(macOS/Linux)
  • %APPDATA%\uv\uv.toml(Windows)
主要环境变量
变量用途
UV_CACHE_DIR缓存目录位置
UV_PYTHON默认 Python 版本
UV_INDEX_URL默认包索引
UV_NO_CACHE禁用缓存
UV_FROZEN使用锁文件但不更新
UV_LOCKED确认锁文件未更改
UV_COMPILE_BYTECODE编译为 .pyc 文件
UV_LINK_MODE包链接模式(copy、hardlink、symlink)

常见工作流

新项目设置
# Create and enter project
uv init my-project
cd my-project

# Add dependencies
uv add flask sqlalchemy
uv add --dev pytest ruff mypy

# Run application
uv run flask run

# Run tests
uv run pytest
现有项目(使用 requirements.txt)
# Initialize uv project
uv init

# Import dependencies from requirements.txt
uv add $(cat requirements.txt | grep -v "^#" | tr '\n' ' ')

# Or use pip interface
uv venv
uv pip install -r requirements.txt
CI/CD 流水线
# GitHub Actions
- uses: astral-sh/setup-uv@v7
  with:
    enable-cache: true
- run: uv sync --locked
- run: uv run pytest
# GitLab CI
variables:
  UV_CACHE_DIR: .uv-cache
  UV_LINK_MODE: copy
image: ghcr.io/astral-sh/uv:latest
script:
  - uv sync --locked
  - uv run pytest
Docker
FROM python:3.12-slim
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/

WORKDIR /app
COPY pyproject.toml uv.lock ./

# Install dependencies only (for caching)
RUN --mount=type=cache,target=/root/.cache/uv \
    uv sync --locked --no-install-project

# Copy source and install project
COPY . .
RUN --mount=type=cache,target=/root/.cache/uv \
    uv sync --locked

ENV PATH="/app/.venv/bin:$PATH"
CMD ["python", "-m", "my_app"]
direnv 集成
# .envrc
if has uv; then
  VIRTUAL_ENV="$(pwd)/.venv"
  if [[ ! -d "$VIRTUAL_ENV" ]]; then
    uv venv
  fi
  PATH_add "$VIRTUAL_ENV/bin"
  export VIRTUAL_ENV
fi

迁移指南

从 pip + requirements.txt 迁移
# Option 1: Initialize new uv project and import dependencies
uv init
# Extract package names from requirements.txt
cat requirements.txt | grep -v "^#" | grep -v "^-e" | \
  cut -d'=' -f1 | cut -d'>' -f1 | xargs uv add

# Option 2: Keep using requirements.txt with uv's pip interface
uv venv
uv pip install -r requirements.txt

# Option 3: Generate lockfile from requirements.txt
uv pip compile requirements.in -o requirements.txt

主要区别:

  • 使用 uv.lock 代替 requirements.txt 锁定依赖
  • 使用 pyproject.toml 代替 requirements.in 声明依赖
  • 使用 uv run 代替激活 virtualenv
从 Poetry 迁移
# uv can read Poetry's pyproject.toml format
cd existing-poetry-project

# Initialize uv (keeps existing pyproject.toml)
uv sync

# Poetry sections are automatically recognized:
# [tool.poetry.dependencies] -> project dependencies
# [tool.poetry.group.dev.dependencies] -> dev dependencies

迁移 pyproject.toml(可选,但建议迁移):

# Poetry format
[tool.poetry.dependencies]
python = "^3.11"
requests = "^2.28"

[tool.poetry.group.dev.dependencies]
pytest = "^8.0"

# Standard format (uv native)
[project]
requires-python = ">=3.11"
dependencies = ["requests>=2.28"]

[dependency-groups]
dev = ["pytest>=8.0"]

命令对应关系:

Poetryuv
poetry installuv sync
poetry add requestsuv add requests
poetry add -D pytestuv add --dev pytest
poetry remove requestsuv remove requests
poetry run pytestuv run pytest
poetry lockuv lock
poetry builduv build
poetry publishuv publish
从 Pipenv 迁移
# Convert Pipfile to requirements.txt first
pipenv requirements > requirements.txt
pipenv requirements --dev > requirements-dev.txt

# Initialize uv project and import
uv init
cat requirements.txt | grep -v "^#" | xargs uv add
cat requirements-dev.txt | grep -v "^#" | xargs uv add --dev

# Remove old Pipenv files after verification
rm Pipfile Pipfile.lock

命令对应关系:

Pipenvuv
pipenv installuv sync
pipenv install requestsuv add requests
pipenv install --dev pytestuv add --dev pytest
pipenv run pytestuv run pytest
pipenv lockuv lock
pipenv shellsource .venv/bin/activate(或使用 uv run)
来自 pyenv(仅用于 Python 版本管理)
# Install Python versions with uv instead
uv python install 3.11 3.12 3.13

# Pin version for project (creates .python-version)
uv python pin 3.12

# List installed versions
uv python list --only-installed

# uv reads existing .python-version files from pyenv

**注意:**你可以同时使用 pyenv 和 uv——uv 会检测通过 pyenv 安装的 Python。

来自 conda

uv 不能替代 conda 来管理:

  • 非 Python 依赖项(C 库、CUDA 等)
  • 不在 PyPI 上的 conda 专属软件包

对于纯 Python 项目:

# Export conda environment
conda list --export > conda-packages.txt

# Extract Python packages (filter conda-specific ones)
grep -v "^#" conda-packages.txt | grep -v "conda" | cut -d'=' -f1 > packages.txt

# Initialize uv and add packages
uv init
uv add $(cat packages.txt | tr '\n' ' ')

**混合方案:**使用 conda 管理系统依赖项,使用 uv 管理 Python 软件包:

# Conda for non-Python deps
conda create -n myenv python=3.12 cudatoolkit

# Activate conda env, then use uv
conda activate myenv
export UV_SYSTEM_PYTHON=1
uv pip install -r requirements.txt

常见陷阱

1. 在 CI/生产环境中忘记使用 --locked
# Wrong - may update lockfile unexpectedly
uv sync

# Correct - fails if lockfile is outdated (reproducible builds)
uv sync --locked
2. 混用 uv 和 pip 命令
# Don't do this - breaks uv's dependency tracking
pip install some-package
source .venv/bin/activate && pip install another-package

# Do this instead - uv tracks all dependencies
uv add some-package
# Or use uv's pip interface if needed
uv pip install some-package
3. 未提交 uv.lock

必须将 uv.lock 文件提交到版本控制中,以确保构建可复现。否则,不同环境解析出的依赖项可能不同。

# .gitignore - DON'T ignore uv.lock
.venv/
__pycache__/
# uv.lock  <-- DO NOT ADD THIS LINE
4. 在项目环境之外运行命令
# Wrong - uses system Python, not project environment
python script.py
pytest

# Correct - runs within project's virtual environment
uv run python script.py
uv run pytest
5. 手动编辑 uv.lock

切勿手动编辑 uv.lock。它由 uv 自动生成和管理。

# To update a specific package
uv lock --upgrade-package requests

# To upgrade all packages
uv lock --upgrade

# To regenerate from scratch
rm uv.lock && uv lock
6. 误用 --frozen,而非 --locked
# --frozen: Don't update lockfile, but don't verify it either
uv sync --frozen

# --locked: Verify lockfile matches pyproject.toml (use this in CI)
uv sync --locked

故障排查

常见问题
问题原因解决方案
No pyproject.toml目录不正确使用 cd 切换到根目录,或运行 uv init
找不到软件包索引错误/拼写错误检查名称,尝试使用 --index
锁文件过时pyproject 已更改运行 uv lock
Resolver conflict版本冲突尝试运行 uv lock --upgrade
Python 版本不匹配尚未安装运行 uv python install 3.12
构建失败缺少依赖项尝试使用 --no-build-isolation
哈希不匹配缓存损坏运行 uv cache clean
首次运行缓慢缓存为空属正常情况;之后会使用缓存
调试命令
# Check current environment
uv python find
uv pip list

# Verbose output
uv sync -v
uv sync -vv  # More verbose

# Check lockfile status
uv lock --check

# Clear cache
uv cache clean
uv cache prune --ci  # For CI environments

参考资料

  • references/cli-commands.md - CLI 完整参考
  • references/project-management.md - 项目和依赖项管理
  • references/python-versions.md - Python 版本管理
  • references/integrations.md - Docker、CI/CD 和工具集成

外部链接

评论

支持 Markdown