Python中Ruff使用指南

作者:

文章目录
  • Ruff 是一款用 Rust 编写的高性能 Python 代码检查器(linter)和格式化工具(formatter),由 Astral 公司开发。它的目标是作为 Flake8、Black、isort 等多个 Python 工具的统一替代品,提供 10-100 倍的性能提升。
  • # 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”]
  • 工具 功能 性能 备注 Flake8 Lint 基准 需要大量插件 Black Format 基准 社区标准 isort 导入排序 基准 – Ruff Lint + Format + Sort 10-100x 更快 单一工具替代 示例:在 CPython 代码库上(约 200k 行),Ruff 检查耗时 <0.5 秒,而 Flake8 需要数十秒。
  • Ruff 通过 Rust 的高性能实现,将 Python 代码检查、格式化和导入排序统一到一个工具中,带来数量级的性能提升。它与现有工具(Flake8、Black、isort)高度兼容,迁移成本低,是现代 Python 项目的理想选择。 快速开始命令: pip install ruff ruff check –fix ruff format 更多详细信息请访问 Ruff 官方文档。
  • 目录
    • 1. Ruff 简介
      • 核心特性
      • 性能优势
    • 2. 安装 Ruff
      • 推荐安装方式
      • 其他安装方式
      • 验证安装
    • 3. Ruff Linter(代码检查器)
      • 基本用法
      • 规则配置
      • 推荐规则集
      • 自动修复安全级别
      • 错误抑制
      • 退出码
    • 4. Ruff Formatter(代码格式化工具)
      • 基本用法
      • 设计理念
      • 配置选项
      • 格式化抑制
      • 与 Linter 的规则冲突
    • 5. 完整配置示例
      • 6. 最佳实践
        • 在项目中使用
        • Git 预提交钩子
        • CI/CD 集成
        • 编辑器集成
      • 7. 性能对比
        • 8. 总结
          • VSCode 中配置和使用 Ruff 的完整指南
            • 1. 安装 Ruff VSCode 扩展
              • 方式一:图形界面安装
              • 方式二:命令行安装
            • 2. 基础配置(推荐设置)
              • 核心配置(在settings.json中)
            • 3. 高级配置选项
              • 3.1 全局设置(在settings.json中)
              • 3.2 项目级配置(推荐)
              • 3.3 工作区特定配置
            • 4. 使用技巧
              • 4.1 手动触发功能
              • 4.2 命令面板常用命令
              • 4.3 与 Black 的迁移
            • 5. 常见问题解决
              • 5.1 扩展安装后无反应
              • 5.2 与 Pyright 类型检查冲突
              • 5.3 格式化与 Black 不一致
              • 5.4 性能问题(大文件卡顿)
            • 6. 调试和日志
              • 启用详细日志
              • 检查 Ruff 配置
            • 7. 版本要求和建议
              • 8. 完整配置示例
                • 推荐的生产环境配置

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

            • 极致性能:比现有工具快 10-100 倍
            • 🐍 pip 安装:通过 pip install ruff 即可安装
            • 🛠️ 统一工具:同时替代 Flake8、Black、isort、pydocstyle、pyupgrade、autoflake 等
            • 📦 内置缓存:自动跳过未更改的文件
            • 🔧 自动修复:支持大量规则的自动修复
            • 📏 800+ 内置规则:包含主流 Flake8 插件的重新实现
            • ⌨️ 编辑器集成:官方支持 VS Code 等主流编辑器
            • 🌎 Monorepo 友好:支持分层级联配置

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

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

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

            # 使用 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 选项
            

            # 检查当前目录所有 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
            

            • 0:未发现 violations 或所有问题已自动修复
            • 1:发现 violations
            • 2:异常终止(配置错误、CLI 选项无效或内部错误)

            # 格式化当前目录所有 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% 以上的兼容性。主要差异:

            • 性能显著提升
            • 支持更多配置选项(引号风格、缩进风格等)
            • 格式化 f-string 表达式部分

            # 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
            

            使用 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
            ]
            

            # 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"]
            

            # 1. 检查并修复代码
            ruff check --fix
            
            # 2. 格式化代码
            ruff format
            
            # 3. 仅排序导入
            ruff check --select I --fix
            
            # 4. 检查未使用的 noqa 指令
            ruff check --extend-select RUF100 --fix
            

            # .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
            

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

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

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

            工具 功能 性能 备注
            Flake8 Lint 基准 需要大量插件
            Black Format 基准 社区标准
            isort 导入排序 基准
            Ruff Lint + Format + Sort 10-100x 更快 单一工具替代

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

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

            快速开始命令

            pip install ruff
            ruff check --fix
            ruff format
            

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

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

            code --install-extension charliermarsh.ruff
            

            前提条件

            • VSCode 版本 ≥ 1.74.0(推荐 ≥ 1.80.0)
            • Python 3.7+ (推荐 3.10+)
            • 系统已安装 Ruff(扩展会自动检测或使用内置版本)

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

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

            配置说明

            • editor.formatOnSave :保存时自动格式化代码
            • source.fixAll.ruff :保存时自动修复可修复的 lint 错误
            • source.organizeImports.ruff :保存时自动排序导入语句
            • editor.defaultFormatter :将 Ruff 设为 Python 文件的默认格式化工具

            {
                // 启用/禁用 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"
            }
            

            在项目根目录创建 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
            

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

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

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

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

            • Ruff: Show Logs – 显示 Ruff 日志
            • Ruff: Restart Server – 重启语言服务器
            • Ruff: Run Linting – 运行代码检查
            • Ruff: Format Document – 格式化当前文档
            • Ruff: Organize Imports – 排序导入语句

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

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

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

            解决方案

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

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

            解决方案

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

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

            解决方案

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

            解决方案

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

            settings.json 中:

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

            在终端运行:

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

            组件 最低版本 推荐版本
            VSCode 1.74.0 1.80.0+
            Ruff 扩展 2024.32.0 最新版
            Ruff CLI 0.5.3 0.9.8+
            Python 3.7 3.10+

            建议定期更新

            # 更新 Ruff CLI
            pip install --upgrade ruff
            
            # 更新 VSCode 扩展
            # 在扩展面板点击更新按钮
            

            // .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使用内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!

            您可能感兴趣的文章:

            • python代码检查工具pylint 让你的python更规范
            • python中pylint使用方法(pylint代码检查)
            • python设置检查点简单实现代码
            • 使用pycharm和pylint检查python代码规范操作
            • Python中使用md5sum检查目录中相同文件代码分享
            • 21行Python代码实现拼写检查器
            • 使用Python编写文件重复检查器的完整代码
            • 利用python检查磁盘空间使用情况的代码实现
            • Python 调用函数时检查参数的类型是否合规的实现代码
            • Python库coala代码分析和自动化检查改进工具使用探索

            站内搜索