TL;DR: Ruff 是一个用 Rust 编写的 Python 代码检查工具(linter + formatter),速度比 Flake8 快 10-100 倍。它能在 0.5 秒内检查完一个包含 30 万行代码的超大型项目。2026 年,Ruff 已经成为 Python 生态的事实标准代码质量工具,被 Instagram、PyTorch、Jupyter、Apache Airflow 等知名项目采用。本文将带你从零开始使用 Ruff,包括安装、配置、替换 Flake8/Black/isort 的完整迁移指南。
一、Ruff 是什么?
Ruff 由 Astral 团队开发(也是 uv 的同一团队),用 Rust 编写,定位为 Python 生态的一体化代码检查工具。它集成了以下多个独立工具的功能:
| 被替代工具 | 功能 | Ruff 规则前缀 |
|---|---|---|
| Flake8 | 代码风格检查 | F, E, W |
| Black | 代码格式化 | - |
| isort | import 排序 | I |
| pyupgrade | Python 版本升级建议 | UP |
| pylint | 高级代码检查 | PL, SIM, C901 |
| autoflake | 自动移除无用 import | F401, F841 |
为什么 Ruff 这么快?
- Rust 编译:Rust 的性能远超 Python,解析速度呈数量级差异
- 并行处理:自动利用多核 CPU 并行扫描文件
- 零依赖:不需要 Python 运行时,单一二进制文件即可运行
- 增量缓存:只检查变更的文件,二次运行几乎瞬时完成
Ruff 的 GitHub 仓库:https://github.com/astral-sh/ruff ⭐ 截至 2026 年已突破 35,000 Star。
二、安装 Ruff
Ruff 支持多种安装方式,推荐使用 pip 或官方安装脚本:
# 方式 1:使用 pip(推荐)
pip install ruff
# 方式 2:使用 uv(更快)
uv tool install ruff
# 方式 3:macOS Homebrew
brew install ruff
# 方式 4:官方安装脚本
curl -LsSf https://astral.sh/ruff/install.sh | sh
# 验证安装
ruff --version
# 输出:ruff 0.9.x
安装完成后,Ruff 提供了两个主要命令:
ruff check:代码检查(linter 模式)ruff format:代码格式化(formatter 模式)
三、快速上手:5 分钟检查你的项目
创建一个测试文件 hello.py:
import os
import sys
import json # unused
def hello_world():
x=1+2
print("hello world")
return x
if __name__ == "__main__":
hello_world()
3.1 运行代码检查
ruff check hello.py
输出示例:
hello.py:1:8: F401 [*] `os` imported but unused
hello.py:2:8: F401 [*] `sys` imported but unused
hello.py:3:8: F401 [*] `json` imported but unused
hello.py:5:1: W293 [*] Blank line contains whitespace
hello.py:7:6: E225 [*] Missing whitespace around operator
Found 5 errors.
[*] 5 fixable with the `--fix` option.
Ruff 精准识别了 5 个问题:3 个未使用的 import、1 个多余空行、1 个运算符周围缺少空格。每个错误都标注了是否可以用 --fix 自动修复。
3.2 自动修复
ruff check --fix hello.py
执行后文件内容自动修正:
def hello_world():
x = 1 + 2
print("hello world")
return x
if __name__ == "__main__":
hello_world()
3.3 代码格式化
ruff format hello.py
ruff format 类似于 Black,会自动调整缩进、空行、引号风格等,确保整个项目代码风格统一。
四、配置文件详解
在项目根目录创建 pyproject.toml 来配置 Ruff:
[tool.ruff]
# 目标 Python 版本
target-version = "py312"
# 行长度限制
line-length = 88
# 要检查的目录
src = ["src", "tests"]
# 排除的目录
exclude = [
".git",
".venv",
"__pycache__",
"build",
"dist",
]
[tool.ruff.lint]
# 启用的规则集
select = [
"E", # pycodestyle 错误
"W", # pycodestyle 警告
"F", # pyflakes
"I", # isort(import 排序)
"UP", # pyupgrade(版本升级建议)
"B", # flake8-bugbear(常见 bug 模式)
"SIM", # flake8-simplify(代码简化)
"RUF", # Ruff 自带规则
]
# 忽略的规则
ignore = [
"E501", # 行太长(交给 formatter 处理)
"E402", # import 不在文件顶部(某些脚本需要)
]
# 最大允许复杂度
mccabe.max-complexity = 10
[tool.ruff.lint.per-file-ignores]
# 测试文件忽略部分规则
"tests/**/*.py" = ["S101", "PLR2004"]
# 迁移文件忽略所有规则
"**/migrations/*.py" = ["ALL"]
[tool.ruff.format]
# 引号风格:单引号或双引号
quote-style = "double"
# 缩进类型
indent-style = "space"
# 末尾换行
skip-magic-trailing-comma = false
4.1 常用规则集说明
| 规则集 | 说明 | 典型规则 |
|---|---|---|
| E/W | pycodestyle 风格检查 | E501 行太长,W292 文件末尾缺少换行 |
| F | pyflakes 错误检测 | F401 未使用 import,F841 未使用变量 |
| I | import 排序 | I001 import 顺序不正确 |
| UP | Python 版本升级 | UP006 使用 list 而非 typing.List |
| B | bugbear 常见 bug | B006 可变默认参数,B007 未使用循环变量 |
| SIM | 代码简化 | SIM101 重复 isinstance,SIM108 使用三元表达式 |
| RUF | Ruff 自有规则 | RUF001 模糊字符,RUF005 展开而非拼接 |
五、替换 Black/isort/Flake8 完整迁移指南
如果你的项目之前使用 Black + isort + Flake8 组合,可以完全迁移到 Ruff。
5.1 卸载旧工具
pip uninstall black isort flake8 autoflake pyupgrade -y
5.2 配置 Ruff 行为兼容
在 pyproject.toml 中添加与 Black 兼容的配置:
[tool.ruff]
line-length = 88 # Black 默认行宽
target-version = "py312"
[tool.ruff.format]
quote-style = "double" # Black 默认双引号
indent-style = "space"
[tool.ruff.lint]
select = ["E", "W", "F", "I"]
5.3 批量修复整个项目
# 第一步:格式化所有 Python 文件
ruff format .
# 第二步:检查并自动修复
ruff check --fix .
# 第三步:查看剩余问题(不自动修复)
ruff check .
5.4 与 pre-commit 集成
创建 .pre-commit-config.yaml:
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.9.0
hooks:
# 先格式化
- id: ruff-format
# 再检查
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
安装 pre-commit hook:
pip install pre-commit
pre-commit install
现在每次 git commit 时,Ruff 会自动格式化和检查暂存的文件。
六、CI/CD 集成实战
6.1 GitHub Actions
name: Ruff Check
on: [push, pull_request]
jobs:
ruff:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Install Ruff
run: pip install ruff
- name: Run Ruff format check
run: ruff format --check .
- name: Run Ruff lint
run: ruff check --output-format=github .
6.2 GitLab CI
ruff:
image: python:3.12-slim
stage: test
script:
- pip install ruff
- ruff format --check .
- ruff check .
allow_failure: true # 初期可以先允许失败
6.3 在大型项目中优化性能
对于超大型项目,可以使用以下优化策略:
# 只检查变更的文件(CI 场景)
ruff check --diff .
# 输出 SARIF 格式(用于 GitHub Code Scanning)
ruff check --output-format=sarif . > results.sarif
# 只检查特定规则
ruff check --select=F,E .
# 查看 Ruff 的配置和缓存状态
ruff check --show-settings .
七、Ruff vs 竞品对比
| 特性 | Ruff | Flake8 | Black + isort |
|---|---|---|---|
| 语言 | Rust | Python | Python |
| 速度 | ⚡ 极快(毫秒级) | 慢(秒级) | 中等 |
| 功能范围 | Linter + Formatter | 仅 Linter | 仅 Formatter |
| 插件生态 | 内置规则 | 丰富插件 | 插件扩展 |
| 自动修复 | ✅ 支持 | ❌ 不支持 | ✅ 支持 |
| 配置方式 | pyproject.toml | .flake8/.cfg | pyproject.toml |
| Python 依赖 | 无需 Python | 需要 | 需要 |
性能实测
在一个 50 万行代码的项目中:
- Ruff check:0.3 秒
- Flake8:45 秒
- pylint:120 秒
Ruff 比 Flake8 快约 150 倍,比 pylint 快约 400 倍。
八、进阶用法
8.1 自定义规则
Ruff 支持通过 pyproject.toml 自定义规则的严重级别:
[tool.ruff.lint]
select = ["E", "F", "W"]
# 将某些规则设为警告而非错误
[tool.ruff.lint.flake8-errmsg]
max-string-length = 20
[tool.ruff.lint.pydocstyle]
convention = "google" # 或 "numpy", "pep257"
8.2 与 IDE 集成
VS Code:安装官方 Ruff 扩展,支持: - 实时 lint 检查 - 保存时自动 format - 一键修复建议
// .vscode/settings.json
{
"[python]": {
"editor.defaultFormatter": "charliermarsh.ruff",
"editor.codeActionsOnSave": {
"source.fixAll.ruff": "explicit"
}
}
}
PyCharm:通过 External Tools 配置:
- 打开 Settings → Tools → External Tools
- 添加 Ruff:Program 为 ruff,Arguments 为 check --fix $FilePath$
8.3 增量检查(Watch 模式)
# 监听文件变化,自动重新检查
ruff check --watch .
8.4 生成 HTML 报告
# 输出 JSON 格式,可以用 jq 处理
ruff check --output-format=json . | jq '.'
# 或使用 sarif 格式配合 GitHub Code Scanning
ruff check --output-format=sarif . > ruff-results.sarif
九、常见问题
Q1:Ruff 能完全替代 Flake8 吗?
大部分场景可以。Ruff 内置了 Flake8 的大部分规则(E、W、F 系列),以及一些流行插件的规则(bugbear、eradicate 等)。但如果你使用了非常小众的 Flake8 插件,可能需要确认 Ruff 是否有对应实现。
Q2:Ruff 能替代 pylint 吗?
不完全可以。Ruff 侧重于代码风格和常见 bug 检测,而 pylint 有更深入的代码质量分析(如复杂度评分、重复代码检测)。对于日常开发,Ruff 已经足够;对于严格的质量审计,可以 Ruff + pylint 配合使用。
Q3:Ruff 的 --fix 安全吗?
非常安全。Ruff 的自动修复仅针对有明确修复策略的规则,不会做语义层面的改动。修复前建议先用 ruff check --diff . 预览变更。
Q4:Ruff 支持哪些 Python 版本?
Ruff 本身支持 Python 3.7 - 3.13 的代码检查。通过 target-version 配置,可以指定目标 Python 版本并获取相应的升级建议。
十、总结
Ruff 正在成为 Python 生态的代码质量基础设施。凭借 Rust 带来的极致性能、丰富的内置规则、以及一体化的 linter + formatter 体验,它让 Python 项目的代码质量管理变得前所未有的简单和高效。
行动建议:
- 用
pip install ruff安装 - 在项目中运行
ruff check --fix .+ruff format . - 配置
pyproject.toml自定义规则 - 集成到 pre-commit 和 CI/CD 流水线
你的项目代码质量会立刻得到一个巨大的提升,而整个过程只需要几分钟。
相关链接:
- Ruff 官方文档:https://docs.astral.sh/ruff/
- Ruff GitHub:https://github.com/astral-sh/ruff
- uv 工具(Ruff 同团队):https://docs.astral.sh/uv/
- 相关资源:linux-tutorials/linux-fileformat.md — 了解 Python 文件格式
- 相关资源:linux-tutorials/ubuntu-dependency.md — Python 包管理基础