python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python Ruff使用

Python中Ruff使用指南

作者:言之。

Ruff是一款基于Rust的高性能Python代码检查与格式化工具,旨在替代Flake8、Black等传统工具,下面就来介绍一下Ruff使用指南,感兴趣的可以了解一下

1. Ruff 简介

Ruff 是一款用 Rust 编写的高性能 Python 代码检查器(linter)和格式化工具(formatter),由 Astral 公司开发。它的目标是作为 Flake8、Black、isort 等多个 Python 工具的统一替代品,提供 10-100 倍的性能提升。

核心特性

性能优势

Ruff 的性能提升带来了显著的开发体验改善。以下是来自实际项目的反馈:

“Ruff 快到有时候我故意在代码里加个 bug 来确认它真的在运行检查” —— FastAPI 创始人 Sebastián Ramírez

“在我 25 万行的 dagster 模块上,pylint 需要 2.5 分钟,而 Ruff 检查整个代码库只需 0.4 秒” —— Elementl 创始人 Nick Schrock

2. 安装 Ruff

推荐安装方式

# 使用 uv(推荐)
uv tool install ruff@latest          # 全局安装
uv add --dev ruff                    # 添加到项目开发依赖

# 使用 pip
pip install ruff

# 使用 pipx
pipx install ruff

# 使用 uvx(无需安装)
uvx ruff check                       # 直接运行检查
uvx ruff format                      # 直接运行格式化

其他安装方式

# macOS/Linux 独立安装脚本
curl -LsSf https://astral.sh/ruff/install.sh | sh

# Windows 独立安装脚本
powershell -c "irm https://astral.sh/ruff/install.ps1 | iex"

# Homebrew (macOS/Linux)
brew install ruff

# Conda
conda install -c conda-forge ruff

# Docker
docker run -v .:/io --rm ghcr.io/astral-sh/ruff check

验证安装

ruff --version
ruff check --help          # 查看 linter 选项
ruff format --help         # 查看 formatter 选项

3. Ruff Linter(代码检查器)

基本用法

# 检查当前目录所有 Python 文件
ruff check

# 检查并自动修复问题
ruff check --fix

# 监听文件变化并重新检查
ruff check --watch

# 检查指定路径
ruff check path/to/code/
ruff check path/to/file.py

# 检查并显示所有可用修复(包括不安全修复)
ruff check --fix --unsafe-fixes

# 退出码为 0 即使发现 violations
ruff check --exit-zero

规则配置

Ruff 使用类似 Flake8 的规则代码系统(如 F401E501)。规则通过 pyproject.tomlruff.toml 配置:

# pyproject.toml
[tool.ruff.lint]
# 启用规则
select = ["E", "F", "B", "UP", "SIM", "I"]

# 忽略特定规则
ignore = ["E501", "F401"]

# 自动修复设置
fixable = ["ALL"]
unfixable = ["F401"]

推荐规则集

[tool.ruff.lint]
select = [
    "E",    # pycodestyle 错误
    "F",    # Pyflakes
    "UP",   # pyupgrade
    "B",    # flake8-bugbear
    "SIM",  # flake8-simplify
    "I",    # isort
]

自动修复安全级别

Ruff 将修复分为安全修复不安全修复

默认仅启用安全修复。启用不安全修复:

ruff check --fix --unsafe-fixes

错误抑制

# 忽略特定规则
x = 1  # noqa: F841

# 忽略多个规则
i = 1  # noqa: E741, F841

# 忽略所有 violations
y = 2  # noqa

# 文件级忽略(放在文件顶部)
# ruff: noqa

# 文件级忽略特定规则
# ruff: noqa: F401, E501

退出码

4. Ruff Formatter(代码格式化工具)

基本用法

# 格式化当前目录所有 Python 文件
ruff format

# 格式化指定路径
ruff format path/to/code/
ruff format path/to/file.py

# 检查格式但不写入(用于 CI)
ruff format --check

# 格式化并显示差异
ruff format --diff

设计理念

Ruff Formatter 是 Black 的替代品,保持 99.9% 以上的兼容性。主要差异:

配置选项

# pyproject.toml
[tool.ruff]
line-length = 88           # 行长度限制(默认 88)

[tool.ruff.format]
quote-style = "double"     # 引号风格: single/double/preserve
indent-style = "space"     # 缩进风格: space/tab
line-ending = "auto"       # 行尾: auto/lf/crlf
docstring-code-format = false  # 是否格式化 docstring 中的代码示例
docstring-code-line-length = "dynamic"  # docstring 代码行长度

格式化抑制

# fmt: off
not_formatted = 3
also_not_formatted = 4
# fmt: on

# 跳过单个语句
a = [1, 2, 3, 4, 5]  # fmt: skip

与 Linter 的规则冲突

使用 Formatter 时建议禁用以下 Linter 规则:

[tool.ruff.lint]
ignore = [
    "W191",  # tab-indentation
    "E111",  # indentation-with-invalid-multiple
    "E114",  # indentation-with-invalid-multiple-comment
    "E117",  # over-indented
    "D206",  # docstring-tab-indentation
    "D300",  # triple-single-quotes
    "Q000",  # bad-quotes-inline-string
    "Q001",  # bad-quotes-multiline-string
    "Q002",  # bad-quotes-docstring
    "Q003",  # avoidable-escaped-quote
    "COM812", # missing-trailing-comma
    "COM819", # prohibited-trailing-comma
]

5. 完整配置示例

# pyproject.toml
[tool.ruff]
# 全局设置
line-length = 88
target-version = "py38"
include = ["*.py", "*.pyi", "**/pyproject.toml"]
exclude = [".git", "__pycache__", "build", "dist"]

[tool.ruff.lint]
# 启用规则
select = ["E", "F", "B", "UP", "SIM", "I"]

# 忽略特定规则
ignore = ["E501", "F401"]

# 自动修复设置
fixable = ["ALL"]
unfixable = []

# 按文件忽略规则
[tool.ruff.lint.per-file-ignores]
"__init__.py" = ["F401"]  # 允许未使用的导入
"tests/**/*.py" = ["B"]   # 测试文件不检查 bugbear

[tool.ruff.format]
# 格式化设置
quote-style = "double"
indent-style = "space"
line-ending = "auto"
docstring-code-format = true

# isort 设置
[tool.ruff.lint.isort]
known-first-party = ["my_package"]
section-order = ["future", "standard-library", "third-party", "first-party", "local-folder"]

6. 最佳实践

在项目中使用

# 1. 检查并修复代码
ruff check --fix

# 2. 格式化代码
ruff format

# 3. 仅排序导入
ruff check --select I --fix

# 4. 检查未使用的 noqa 指令
ruff check --extend-select RUF100 --fix

Git 预提交钩子

# .pre-commit-config.yaml
repos:
  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.8.0
    hooks:
      # Linter
      - id: ruff
        args: [--fix, --exit-non-zero-on-fix]
      # Formatter
      - id: ruff-format

CI/CD 集成

# GitHub Actions
- name: Run Ruff
  run: |
    pip install ruff
    ruff check --exit-non-zero-on-fix
    ruff format --check

编辑器集成

VS Code:安装官方插件 Ruff,自动启用检查和格式化

其他编辑器:通过 LSP 或插件支持,详见 编辑器集成文档

7. 性能对比

工具功能性能备注
Flake8Lint基准需要大量插件
BlackFormat基准社区标准
isort导入排序基准-
RuffLint + Format + Sort10-100x 更快单一工具替代

示例:在 CPython 代码库上(约 200k 行),Ruff 检查耗时 <0.5 秒,而 Flake8 需要数十秒。

8. 总结

Ruff 通过 Rust 的高性能实现,将 Python 代码检查、格式化和导入排序统一到一个工具中,带来数量级的性能提升。它与现有工具(Flake8、Black、isort)高度兼容,迁移成本低,是现代 Python 项目的理想选择。

快速开始命令

pip install ruff
ruff check --fix
ruff format

更多详细信息请访问 Ruff 官方文档

VSCode 中配置和使用 Ruff 的完整指南

1. 安装 Ruff VSCode 扩展

方式一:图形界面安装

  1. 打开 VSCode
  2. 点击左侧活动栏的扩展图标(或按 Ctrl+Shift+X
  3. 在搜索框中输入 “Ruff”
  4. 找到 Ruff 扩展(作者:charliermarsh,官方扩展)
  5. 点击"安装"按钮

方式二:命令行安装

code --install-extension charliermarsh.ruff

前提条件

2. 基础配置(推荐设置)

在 VSCode 设置中(文件 > 首选项 > 设置 或按 Ctrl+,),搜索 “Ruff”,添加以下配置:

核心配置(在settings.json中)

{
    "[python]": {
        "editor.formatOnSave": true,
        "editor.codeActionsOnSave": {
            "source.fixAll.ruff": "explicit",
            "source.organizeImports.ruff": "explicit"
        },
        "editor.defaultFormatter": "charliermarsh.ruff"
    }
}

配置说明

3. 高级配置选项

3.1 全局设置(在settings.json中)

{
    // 启用/禁用 Ruff 扩展
    "ruff.enable": true,
    
    // 指定 Python 解释器路径(如果扩展无法自动检测)
    "ruff.interpreter": ["/usr/bin/python3"],
    
    // 指定 Ruff 可执行文件路径
    "ruff.path": ["/home/user/.local/bin/ruff"],
    
    // 行长度限制
    "ruff.lineLength": 88,
    
    // 启用的规则集
    "ruff.lint.select": ["E", "F", "W", "I"],
    
    // 忽略的规则
    "ruff.lint.ignore": ["E501"],
    
    // 排除的文件/目录
    "ruff.exclude": ["**/tests/**", "**/vendor/**"],
    
    // 启用预览特性
    "ruff.lint.preview": true,
    "ruff.format.preview": true,
    
    // 配置优先级
    "ruff.configurationPreference": "filesystemFirst"
}

3.2 项目级配置(推荐)

在项目根目录创建 pyproject.tomlruff.toml

# pyproject.toml
[tool.ruff]
line-length = 88
target-version = "py38"
include = ["*.py", "*.pyi", "**/pyproject.toml"]
exclude = [".git", "__pycache__", "build", "dist"]

[tool.ruff.lint]
# 启用规则
select = ["E", "F", "B", "UP", "SIM", "I"]
# 忽略规则
ignore = ["E501"]
# 自动修复设置
fixable = ["ALL"]
unfixable = []

[tool.ruff.lint.per-file-ignores]
"__init__.py" = ["F401"]
"tests/**/*.py" = ["B"]

[tool.ruff.format]
quote-style = "double"
indent-style = "space"
docstring-code-format = true

3.3 工作区特定配置

创建 .vscode/settings.json(仅对当前工作区生效):

{
    "ruff.configuration": "${workspaceFolder}/pyproject.toml",
    "ruff.logLevel": "info",
    "ruff.trace.server": "messages",
    "python.defaultInterpreterPath": "${workspaceFolder}/venv/bin/python"
}

4. 使用技巧

4.1 手动触发功能

  1. 格式化文档:右键 → “Format Document” 或按 Shift+Alt+F
  2. 快速修复:在错误上按 Ctrl+. 选择修复方案
  3. 排序导入:命令面板 (Ctrl+Shift+P) → “Ruff: Organize Imports”
  4. 运行 Ruff 检查:命令面板 → “Ruff: Run Linting”

4.2 命令面板常用命令

Ctrl+Shift+P 打开命令面板,输入:

4.3 与 Black 的迁移

如果之前使用 Black,确保禁用 Black 并切换到 Ruff:

{
    "python.formatting.provider": "none",
    "[python]": {
        "editor.defaultFormatter": "charliermarsh.ruff"
    }
}

5. 常见问题解决

5.1 扩展安装后无反应

问题:安装后没有代码检查或格式化功能

解决方案

  1. 检查 Ruff 版本:ruff --version(建议 ≥ 0.5.3)
  2. 确保 Python 扩展已安装
  3. 检查 Python 解释器选择是否正确(按 Ctrl+Shift+P → “Python: Select Interpreter”)
  4. 查看输出面板:终端 → 输出 → 选择 “Ruff” 查看日志

5.2 与 Pyright 类型检查冲突

问题:Ruff 和 Pyright 同时运行导致重复提示

解决方案

{
    "python.analysis.diagnosticSeverityOverrides": {
        "reportMissingImports": "none",
        "reportUnusedVariable": "none"
    }
}

5.3 格式化与 Black 不一致

问题:团队同时使用 Black 和 Ruff 导致格式冲突

解决方案

  1. pyproject.toml 中配置 Ruff 的 Black 兼容模式:
[tool.ruff.format]
# Ruff 默认就是 Black 兼容的,无需特殊配置
preview = true  # 启用最新的 Black 兼容特性

5.4 性能问题(大文件卡顿)

解决方案

{
    "ruff.lint.run": "onType",  // 改为 onSave 减少实时检查
    "files.watcherExclude": {
        "**/.ruff_cache/**": true
    }
}

6. 调试和日志

启用详细日志

settings.json 中:

{
    "ruff.logLevel": "debug",
    "ruff.trace.server": "verbose",
    "ruff.logFile": "${workspaceFolder}/.vscode/ruff.log"
}

检查 Ruff 配置

在终端运行:

# 检查当前配置
ruff check --show-settings

# 检查格式化配置
ruff format --show-settings

7. 版本要求和建议

组件最低版本推荐版本
VSCode1.74.01.80.0+
Ruff 扩展2024.32.0最新版
Ruff CLI0.5.30.9.8+
Python3.73.10+

建议定期更新

# 更新 Ruff CLI
pip install --upgrade ruff

# 更新 VSCode 扩展
# 在扩展面板点击更新按钮

8. 完整配置示例

推荐的生产环境配置

// .vscode/settings.json
{
    "[python]": {
        "editor.defaultFormatter": "charliermarsh.ruff",
        "editor.formatOnSave": true,
        "editor.codeActionsOnSave": {
            "source.fixAll.ruff": "explicit",
            "source.organizeImports.ruff": "explicit"
        },
        "editor.rulers": [88],
        "editor.tabSize": 4,
        "editor.insertSpaces": true
    },
    
    "ruff.enable": true,
    "ruff.interpreter": ["${workspaceFolder}/venv/bin/python"],
    "ruff.lint.select": ["E", "F", "B", "UP", "SIM", "I"],
    "ruff.lint.ignore": ["E501", "F403"],
    "ruff.format.preview": true,
    "ruff.lint.preview": true,
    
    "files.associations": {
        "*.pyi": "python"
    }
}

按照以上配置,Ruff 将在 VSCode 中提供流畅的代码检查和格式化体验,大幅提升 Python 开发效率。

到此这篇关于Python中Ruff使用指南的文章就介绍到这了,更多相关Python Ruff使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文