工具链与脚本执行
2026/3/20大约 8 分钟
工具链与脚本执行
使用 uvx 和 uv tool 管理 Python 命令行工具
uvx 概述
uvx 是 uv 提供的工具运行器,类似于 npx(Node.js)或 pipx run。它允许你无需全局安装即可运行 Python 命令行工具。
核心优势
| 特性 | 描述 |
|---|---|
| 即用即走 | 无需预先安装,直接运行 |
| 版本隔离 | 每个工具独立环境,互不冲突 |
| 自动缓存 | 重复运行秒级启动 |
| 版本控制 | 可指定工具的精确版本 |
| 跨项目使用 | 不污染项目依赖 |
运行工具
基本用法
# 运行工具(等同于 pipx run)
uvx ruff check .
# 完整语法
uv tool run ruff check .
# 常用工具示例
uvx black . # 代码格式化
uvx isort . # 导入排序
uvx mypy src/ # 类型检查
uvx pytest # 运行测试
uvx httpie GET example.com # HTTP 客户端
uvx cowsay "Hello!" # 趣味工具
指定版本
# 运行特定版本
uvx ruff@0.1.0 check .
# 使用版本约束
uvx "ruff>=0.1.0,<0.2.0" check .
# 运行最新版本
uvx ruff@latest check .
指定包名
当工具名与包名不同时:
# 从 httpie 包运行 http 命令
uvx --from httpie http GET example.com
# 从 aws-cli 包运行 aws 命令
uvx --from awscli aws s3 ls
# 从 jupyter 包运行 jupyter-lab
uvx --from jupyterlab jupyter lab
# 指定版本
uvx --from "httpie>=3.0" http GET example.com
附加依赖
# 运行时添加额外依赖
uvx --with requests python -c "import requests; print('OK')"
# 多个额外依赖
uvx --with numpy --with pandas python script.py
# 带版本的额外依赖
uvx --with "requests>=2.28" --with "beautifulsoup4>=4.0" python scraper.py
指定 Python 版本
# 使用特定 Python 版本运行
uvx --python 3.11 ruff check .
# 使用最新 Python
uvx --python 3 black .
全局安装工具
uv tool install
将工具永久安装到用户目录:
# 安装工具
uv tool install ruff
# 安装特定版本
uv tool install "ruff==0.1.0"
# 使用特定 Python 版本
uv tool install --python 3.11 mypy
# 带额外依赖安装
uv tool install --with pytest-cov pytest
安装位置
# 查看工具安装目录
uv tool dir
# ~/.local/share/uv/tools/
# 目录结构
~/.local/share/uv/tools/
├── ruff/ # 工具专属环境
│ ├── bin/
│ │ └── ruff # 可执行文件
│ └── lib/
│ └── python3.12/
│ └── site-packages/
└── black/
└── ...
添加到 PATH
安装后需要确保工具目录在 PATH 中:
# 查看 bin 目录
uv tool bin-dir
# ~/.local/bin/
# Linux/macOS - 添加到 shell 配置
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc
# Windows - 添加到用户 PATH
# 在系统环境变量中添加 %USERPROFILE%\.local\bin
列出已安装工具
# 列出所有已安装的工具
uv tool list
# 示例输出
ruff v0.1.9
- ruff
black v23.12.1
- black
- blackd
mypy v1.8.0
- mypy
- stubgen
- stubtest
- dmypy
管理全局工具
升级工具
# 升级单个工具
uv tool upgrade ruff
# 升级所有工具
uv tool upgrade --all
# 升级到特定版本
uv tool upgrade "ruff>=0.2.0"
卸载工具
# 卸载工具
uv tool uninstall ruff
# 卸载多个工具
uv tool uninstall ruff black mypy
重新安装
# 强制重新安装
uv tool install --force ruff
# 更新 Python 版本
uv tool install --python 3.12 --force mypy
常用工具推荐
代码质量工具
# Ruff - 极速 Python Linter
uv tool install ruff
ruff check .
ruff format .
# Black - 代码格式化
uv tool install black
black .
# isort - 导入排序
uv tool install isort
isort .
# MyPy - 静态类型检查
uv tool install mypy
mypy src/
# Pylint - 代码分析
uv tool install pylint
pylint src/
测试工具
# Pytest - 测试框架
uv tool install pytest
pytest
# Tox - 多环境测试
uv tool install tox
tox
# Nox - 自动化测试
uv tool install nox
nox
# Coverage - 覆盖率
uv tool install coverage
coverage run -m pytest
coverage report
文档工具
# MkDocs - 文档生成
uv tool install mkdocs
mkdocs serve
# Sphinx - 文档系统
uv tool install sphinx
sphinx-quickstart
# pdoc - API 文档
uv tool install pdoc
pdoc src/
开发工具
# HTTPie - HTTP 客户端
uv tool install httpie
http GET example.com
# IPython - 增强解释器
uv tool install ipython
ipython
# Jupyter - 交互式笔记本
uv tool install jupyterlab
jupyter lab
# pre-commit - Git Hooks
uv tool install pre-commit
pre-commit install
# Cookiecutter - 项目模板
uv tool install cookiecutter
cookiecutter gh:audreyr/cookiecutter-pypackage
部署工具
# Twine - PyPI 上传
uv tool install twine
twine upload dist/*
# Build - 构建工具
uv tool install build
python -m build
# pip-audit - 安全审计
uv tool install pip-audit
pip-audit
脚本执行
uv run 执行脚本
# 在项目环境中运行脚本
uv run python script.py
# 运行带参数的脚本
uv run python script.py --arg1 value1
# 运行模块
uv run python -m mymodule
# 交互式解释器
uv run python
内联依赖脚本
uv 支持 PEP 723 风格的内联脚本元数据:
#!/usr/bin/env python
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "requests>=2.28",
# "rich>=13.0",
# ]
# ///
import requests
from rich import print
response = requests.get("https://api.github.com")
print(response.json())
运行:
# uv 自动安装脚本声明的依赖
uv run script.py
# 或使用 uvx
uvx script.py
脚本示例
数据处理脚本
#!/usr/bin/env python
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "pandas>=2.0",
# "matplotlib>=3.7",
# ]
# ///
import pandas as pd
import matplotlib.pyplot as plt
# 读取数据
df = pd.read_csv("data.csv")
# 绑图
df.plot(kind="bar")
plt.savefig("output.png")
print("Chart saved!")
Web 爬虫脚本
#!/usr/bin/env python
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "httpx>=0.25",
# "beautifulsoup4>=4.12",
# "rich>=13.0",
# ]
# ///
import httpx
from bs4 import BeautifulSoup
from rich.console import Console
from rich.table import Table
console = Console()
response = httpx.get("https://news.ycombinator.com")
soup = BeautifulSoup(response.text, "html.parser")
table = Table(title="Hacker News Top Stories")
table.add_column("Title")
for item in soup.select(".titleline > a")[:10]:
table.add_row(item.text)
console.print(table)
临时依赖运行
# 不修改项目,临时使用包
uv run --with rich python -c "from rich import print; print('[bold]Hello![/bold]')"
# 组合多个包
uv run --with httpx --with beautifulsoup4 python scraper.py
# 指定版本
uv run --with "pandas>=2.0" --with "numpy>=1.24" python analysis.py
工具与项目的关系
项目依赖 vs 全局工具
┌─────────────────────────────────────────────────────────────────────────┐
│ 工具使用场景决策树 │
├─────────────────────────────────────────────────────────────────────────┤
│ │
│ 这个工具是项目必需的吗? │
│ │ │
│ Yes ─┴─ No │
│ │ │ │
│ ▼ │ │
│ 项目依赖 │ │
│ uv add │ │
│ ruff │ │
│ │ │
│ ▼ │
│ 经常使用吗? │
│ │ │
│ Yes ──┴── No │
│ │ │ │
│ ▼ │ │
│ 全局安装 │ │
│ uv tool │ │
│ install │ │
│ ruff│ │
│ │ │
│ ▼ │
│ 临时运行 │
│ uvx ruff │
│ │
└─────────────────────────────────────────────────────────────────────────┘
使用建议
| 场景 | 推荐方式 | 示例 |
|---|---|---|
| 项目开发依赖 | uv add --dev | pytest, ruff |
| 个人工作站工具 | uv tool install | httpie, ipython |
| 一次性使用 | uvx | cowsay, quickstart |
| CI/CD 工具 | uvx | 版本可控,不污染环境 |
高级用法
工具别名
创建别名简化常用命令:
# ~/.bashrc 或 ~/.zshrc
# 使用 uvx 运行工具
alias lint='uvx ruff check'
alias fmt='uvx ruff format'
alias typecheck='uvx mypy'
# 使用特定版本
alias pytest311='uv run --python 3.11 pytest'
预热缓存
在 CI 中预先缓存工具:
# 预先安装常用工具到缓存
uvx ruff --version
uvx black --version
uvx mypy --version
# 后续运行使用缓存,速度更快
uvx ruff check .
离线运行
# 确保工具已缓存
uvx ruff --version
# 离线运行
UV_OFFLINE=true uvx ruff check .
自定义工具环境
# 创建带特定配置的工具
uv tool install ruff \
--with ruff-lsp \
--python 3.12
与 pipx 对比
┌─────────────────────────────────────────────────────────────────────────┐
│ uvx vs pipx │
├─────────────────────────────────────────────────────────────────────────┤
│ │
│ 特性 uvx pipx │
│ ────────────────────────────────────────────────────────────────── │
│ 运行速度 极快(Rust 实现) 较慢(Python 实现) │
│ 临时运行 uvx <tool> pipx run <tool> │
│ 全局安装 uv tool install pipx install │
│ 依赖隔离 ✓ ✓ │
│ 版本指定 ✓ (@version) ✓ (--spec) │
│ 额外依赖 --with --spec │
│ Python 版本 --python --python │
│ 缓存 自动 需要配置 │
│ 与 uv 集成 原生 无 │
│ │
└─────────────────────────────────────────────────────────────────────────┘
从 pipx 迁移
# pipx 命令 # uv 等价命令
pipx run ruff check . uvx ruff check .
pipx install ruff uv tool install ruff
pipx upgrade ruff uv tool upgrade ruff
pipx uninstall ruff uv tool uninstall ruff
pipx list uv tool list
pipx run --spec httpie http uvx --from httpie http
CI/CD 集成
GitHub Actions
name: Lint and Type Check
on: [push, pull_request]
jobs:
quality:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install uv
uses: astral-sh/setup-uv@v3
- name: Lint
run: uvx ruff check .
- name: Format check
run: uvx ruff format --check .
- name: Type check
run: uvx mypy src/
GitLab CI
lint:
image: python:3.12
before_script:
- pip install uv
script:
- uvx ruff check .
- uvx ruff format --check .
- uvx mypy src/
Pre-commit 集成
# .pre-commit-config.yaml
repos:
- repo: local
hooks:
- id: ruff-check
name: ruff check
entry: uvx ruff check
language: system
types: [python]
- id: ruff-format
name: ruff format
entry: uvx ruff format
language: system
types: [python]
- id: mypy
name: mypy
entry: uvx mypy
language: system
types: [python]
故障排除
常见问题
1. 工具找不到
# 检查 PATH
echo $PATH
# 确认 bin 目录
uv tool bin-dir
# 手动添加到 PATH
export PATH="$(uv tool bin-dir):$PATH"
2. 版本冲突
# 清理并重新安装
uv tool uninstall ruff
uv tool install ruff
# 强制使用特定版本
uvx ruff@0.1.0 check .
3. 缓存问题
# 清理工具缓存
uv cache clean
# 强制重新下载
uvx --refresh ruff check .
4. Python 版本不兼容
# 指定兼容的 Python 版本
uv tool install --python 3.11 some-tool
# 运行时指定
uvx --python 3.11 some-tool
调试技巧
# 详细输出
uvx --verbose ruff check .
# 查看安装的工具详情
ls -la $(uv tool dir)
# 检查工具环境
cat $(uv tool dir)/ruff/pyvenv.cfg
最佳实践
个人工作站配置
# 安装常用工具
uv tool install ruff
uv tool install mypy
uv tool install black
uv tool install httpie
uv tool install ipython
uv tool install pre-commit
# 配置 shell 别名
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc
项目开发配置
# pyproject.toml
[tool.uv]
dev-dependencies = [
"pytest>=7.0",
"pytest-cov>=4.0",
"ruff>=0.1.0",
"mypy>=1.0",
]
# Makefile
.PHONY: lint format typecheck test
lint:
uv run ruff check .
format:
uv run ruff format .
typecheck:
uv run mypy src/
test:
uv run pytest
总结
| 操作 | 命令 |
|---|---|
| 临时运行工具 | uvx <tool> |
| 指定版本运行 | uvx <tool>@<version> |
| 从包运行命令 | uvx --from <pkg> <cmd> |
| 全局安装 | uv tool install <tool> |
| 列出工具 | uv tool list |
| 升级工具 | uv tool upgrade <tool> |
| 卸载工具 | uv tool uninstall <tool> |
| 运行脚本 | uv run python script.py |
关键要点
- uvx 是你的瑞士军刀 - 无需安装即可运行任何工具
- 常用工具全局安装 - 节省每次解析时间
- 一次性工具用 uvx - 保持系统干净
- 内联脚本依赖 - PEP 723 让脚本自包含