Python中Ruff使用指南
1. Ruff 簡介
Ruff 是一款用 Rust 編寫的高性能 Python 代碼檢查器(linter)和格式化工具(formatter),由 Astral 公司開發(fā)。它的目標(biāo)是作為 Flake8、Black、isort 等多個(gè) Python 工具的統(tǒng)一替代品,提供 10-100 倍的性能提升。
核心特性
- ? 極致性能:比現(xiàn)有工具快 10-100 倍
- ?? pip 安裝:通過
pip install ruff即可安裝 - ??? 統(tǒng)一工具:同時(shí)替代 Flake8、Black、isort、pydocstyle、pyupgrade、autoflake 等
- ?? 內(nèi)置緩存:自動(dòng)跳過未更改的文件
- ?? 自動(dòng)修復(fù):支持大量規(guī)則的自動(dòng)修復(fù)
- ?? 800+ 內(nèi)置規(guī)則:包含主流 Flake8 插件的重新實(shí)現(xiàn)
- ?? 編輯器集成:官方支持 VS Code 等主流編輯器
- ?? Monorepo 友好:支持分層級聯(lián)配置
性能優(yōu)勢
Ruff 的性能提升帶來了顯著的開發(fā)體驗(yàn)改善。以下是來自實(shí)際項(xiàng)目的反饋:
“Ruff 快到有時(shí)候我故意在代碼里加個(gè) bug 來確認(rèn)它真的在運(yùn)行檢查” —— FastAPI 創(chuàng)始人 Sebastián Ramírez
“在我 25 萬行的 dagster 模塊上,pylint 需要 2.5 分鐘,而 Ruff 檢查整個(gè)代碼庫只需 0.4 秒” —— Elementl 創(chuàng)始人 Nick Schrock
2. 安裝 Ruff
推薦安裝方式
# 使用 uv(推薦) uv tool install ruff@latest # 全局安裝 uv add --dev ruff # 添加到項(xiàng)目開發(fā)依賴 # 使用 pip pip install ruff # 使用 pipx pipx install ruff # 使用 uvx(無需安裝) uvx ruff check # 直接運(yùn)行檢查 uvx ruff format # 直接運(yùn)行格式化
其他安裝方式
# macOS/Linux 獨(dú)立安裝腳本 curl -LsSf https://astral.sh/ruff/install.sh | sh # Windows 獨(dú)立安裝腳本 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
驗(yàn)證安裝
ruff --version ruff check --help # 查看 linter 選項(xiàng) ruff format --help # 查看 formatter 選項(xiàng)
3. Ruff Linter(代碼檢查器)
基本用法
# 檢查當(dāng)前目錄所有 Python 文件 ruff check # 檢查并自動(dòng)修復(fù)問題 ruff check --fix # 監(jiān)聽文件變化并重新檢查 ruff check --watch # 檢查指定路徑 ruff check path/to/code/ ruff check path/to/file.py # 檢查并顯示所有可用修復(fù)(包括不安全修復(fù)) ruff check --fix --unsafe-fixes # 退出碼為 0 即使發(fā)現(xiàn) violations ruff check --exit-zero
規(guī)則配置
Ruff 使用類似 Flake8 的規(guī)則代碼系統(tǒng)(如 F401、E501)。規(guī)則通過 pyproject.toml 或 ruff.toml 配置:
# pyproject.toml [tool.ruff.lint] # 啟用規(guī)則 select = ["E", "F", "B", "UP", "SIM", "I"] # 忽略特定規(guī)則 ignore = ["E501", "F401"] # 自動(dòng)修復(fù)設(shè)置 fixable = ["ALL"] unfixable = ["F401"]
推薦規(guī)則集
[tool.ruff.lint]
select = [
"E", # pycodestyle 錯(cuò)誤
"F", # Pyflakes
"UP", # pyupgrade
"B", # flake8-bugbear
"SIM", # flake8-simplify
"I", # isort
]
自動(dòng)修復(fù)安全級別
Ruff 將修復(fù)分為安全修復(fù)和不安全修復(fù):
- 安全修復(fù):保證代碼語義不變,僅移除注釋當(dāng)刪除整個(gè)語句時(shí)
- 不安全修復(fù):可能改變運(yùn)行時(shí)行為、移除注釋或改變異常類型
默認(rèn)僅啟用安全修復(fù)。啟用不安全修復(fù):
ruff check --fix --unsafe-fixes
錯(cuò)誤抑制
# 忽略特定規(guī)則 x = 1 # noqa: F841 # 忽略多個(gè)規(guī)則 i = 1 # noqa: E741, F841 # 忽略所有 violations y = 2 # noqa # 文件級忽略(放在文件頂部) # ruff: noqa # 文件級忽略特定規(guī)則 # ruff: noqa: F401, E501
退出碼
0:未發(fā)現(xiàn) violations 或所有問題已自動(dòng)修復(fù)1:發(fā)現(xiàn) violations2:異常終止(配置錯(cuò)誤、CLI 選項(xiàng)無效或內(nèi)部錯(cuò)誤)
4. Ruff Formatter(代碼格式化工具)
基本用法
# 格式化當(dāng)前目錄所有 Python 文件 ruff format # 格式化指定路徑 ruff format path/to/code/ ruff format path/to/file.py # 檢查格式但不寫入(用于 CI) ruff format --check # 格式化并顯示差異 ruff format --diff
設(shè)計(jì)理念
Ruff Formatter 是 Black 的替代品,保持 99.9% 以上的兼容性。主要差異:
- 性能顯著提升
- 支持更多配置選項(xiàng)(引號風(fēng)格、縮進(jìn)風(fēng)格等)
- 格式化 f-string 表達(dá)式部分
配置選項(xiàng)
# pyproject.toml [tool.ruff] line-length = 88 # 行長度限制(默認(rèn) 88) [tool.ruff.format] quote-style = "double" # 引號風(fēng)格: single/double/preserve indent-style = "space" # 縮進(jìn)風(fēng)格: 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 # 跳過單個(gè)語句 a = [1, 2, 3, 4, 5] # fmt: skip
與 Linter 的規(guī)則沖突
使用 Formatter 時(shí)建議禁用以下 Linter 規(guī)則:
[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] # 全局設(shè)置 line-length = 88 target-version = "py38" include = ["*.py", "*.pyi", "**/pyproject.toml"] exclude = [".git", "__pycache__", "build", "dist"] [tool.ruff.lint] # 啟用規(guī)則 select = ["E", "F", "B", "UP", "SIM", "I"] # 忽略特定規(guī)則 ignore = ["E501", "F401"] # 自動(dòng)修復(fù)設(shè)置 fixable = ["ALL"] unfixable = [] # 按文件忽略規(guī)則 [tool.ruff.lint.per-file-ignores] "__init__.py" = ["F401"] # 允許未使用的導(dǎo)入 "tests/**/*.py" = ["B"] # 測試文件不檢查 bugbear [tool.ruff.format] # 格式化設(shè)置 quote-style = "double" indent-style = "space" line-ending = "auto" docstring-code-format = true # isort 設(shè)置 [tool.ruff.lint.isort] known-first-party = ["my_package"] section-order = ["future", "standard-library", "third-party", "first-party", "local-folder"]
6. 最佳實(shí)踐
在項(xiàng)目中使用
# 1. 檢查并修復(fù)代碼 ruff check --fix # 2. 格式化代碼 ruff format # 3. 僅排序?qū)? ruff check --select I --fix # 4. 檢查未使用的 noqa 指令 ruff check --extend-select RUF100 --fix
Git 預(yù)提交鉤子
# .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,自動(dòng)啟用檢查和格式化
其他編輯器:通過 LSP 或插件支持,詳見 編輯器集成文檔
7. 性能對比
| 工具 | 功能 | 性能 | 備注 |
|---|---|---|---|
| Flake8 | Lint | 基準(zhǔn) | 需要大量插件 |
| Black | Format | 基準(zhǔn) | 社區(qū)標(biāo)準(zhǔn) |
| isort | 導(dǎo)入排序 | 基準(zhǔn) | - |
| Ruff | Lint + Format + Sort | 10-100x 更快 | 單一工具替代 |
示例:在 CPython 代碼庫上(約 200k 行),Ruff 檢查耗時(shí) <0.5 秒,而 Flake8 需要數(shù)十秒。
8. 總結(jié)
Ruff 通過 Rust 的高性能實(shí)現(xiàn),將 Python 代碼檢查、格式化和導(dǎo)入排序統(tǒng)一到一個(gè)工具中,帶來數(shù)量級的性能提升。它與現(xiàn)有工具(Flake8、Black、isort)高度兼容,遷移成本低,是現(xiàn)代 Python 項(xiàng)目的理想選擇。
快速開始命令:
pip install ruff ruff check --fix ruff format
更多詳細(xì)信息請?jiān)L問 Ruff 官方文檔。
VSCode 中配置和使用 Ruff 的完整指南
1. 安裝 Ruff VSCode 擴(kuò)展
方式一:圖形界面安裝
- 打開 VSCode
- 點(diǎn)擊左側(cè)活動(dòng)欄的擴(kuò)展圖標(biāo)(或按
Ctrl+Shift+X) - 在搜索框中輸入 “Ruff”
- 找到 Ruff 擴(kuò)展(作者:charliermarsh,官方擴(kuò)展)
- 點(diǎn)擊"安裝"按鈕
方式二:命令行安裝
code --install-extension charliermarsh.ruff
前提條件
- VSCode 版本 ≥ 1.74.0(推薦 ≥ 1.80.0)
- Python 3.7+ (推薦 3.10+)
- 系統(tǒng)已安裝 Ruff(擴(kuò)展會(huì)自動(dòng)檢測或使用內(nèi)置版本)
2. 基礎(chǔ)配置(推薦設(shè)置)
在 VSCode 設(shè)置中(文件 > 首選項(xiàng) > 設(shè)置 或按 Ctrl+,),搜索 “Ruff”,添加以下配置:
核心配置(在settings.json中)
{
"[python]": {
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.ruff": "explicit",
"source.organizeImports.ruff": "explicit"
},
"editor.defaultFormatter": "charliermarsh.ruff"
}
}
配置說明:
- editor.formatOnSave :保存時(shí)自動(dòng)格式化代碼
- source.fixAll.ruff :保存時(shí)自動(dòng)修復(fù)可修復(fù)的 lint 錯(cuò)誤
- source.organizeImports.ruff :保存時(shí)自動(dòng)排序?qū)胝Z句
- editor.defaultFormatter :將 Ruff 設(shè)為 Python 文件的默認(rèn)格式化工具
3. 高級配置選項(xiàng)
3.1 全局設(shè)置(在settings.json中)
{
// 啟用/禁用 Ruff 擴(kuò)展
"ruff.enable": true,
// 指定 Python 解釋器路徑(如果擴(kuò)展無法自動(dòng)檢測)
"ruff.interpreter": ["/usr/bin/python3"],
// 指定 Ruff 可執(zhí)行文件路徑
"ruff.path": ["/home/user/.local/bin/ruff"],
// 行長度限制
"ruff.lineLength": 88,
// 啟用的規(guī)則集
"ruff.lint.select": ["E", "F", "W", "I"],
// 忽略的規(guī)則
"ruff.lint.ignore": ["E501"],
// 排除的文件/目錄
"ruff.exclude": ["**/tests/**", "**/vendor/**"],
// 啟用預(yù)覽特性
"ruff.lint.preview": true,
"ruff.format.preview": true,
// 配置優(yōu)先級
"ruff.configurationPreference": "filesystemFirst"
}
3.2 項(xiàng)目級配置(推薦)
在項(xiàng)目根目錄創(chuàng)建 pyproject.toml 或 ruff.toml:
# pyproject.toml [tool.ruff] line-length = 88 target-version = "py38" include = ["*.py", "*.pyi", "**/pyproject.toml"] exclude = [".git", "__pycache__", "build", "dist"] [tool.ruff.lint] # 啟用規(guī)則 select = ["E", "F", "B", "UP", "SIM", "I"] # 忽略規(guī)則 ignore = ["E501"] # 自動(dòng)修復(fù)設(shè)置 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 工作區(qū)特定配置
創(chuàng)建 .vscode/settings.json(僅對當(dāng)前工作區(qū)生效):
{
"ruff.configuration": "${workspaceFolder}/pyproject.toml",
"ruff.logLevel": "info",
"ruff.trace.server": "messages",
"python.defaultInterpreterPath": "${workspaceFolder}/venv/bin/python"
}
4. 使用技巧
4.1 手動(dòng)觸發(fā)功能
- 格式化文檔:右鍵 → “Format Document” 或按
Shift+Alt+F - 快速修復(fù):在錯(cuò)誤上按
Ctrl+.選擇修復(fù)方案 - 排序?qū)?/strong>:命令面板 (
Ctrl+Shift+P) → “Ruff: Organize Imports” - 運(yùn)行 Ruff 檢查:命令面板 → “Ruff: Run Linting”
4.2 命令面板常用命令
按 Ctrl+Shift+P 打開命令面板,輸入:
Ruff: Show Logs- 顯示 Ruff 日志Ruff: Restart Server- 重啟語言服務(wù)器Ruff: Run Linting- 運(yùn)行代碼檢查Ruff: Format Document- 格式化當(dāng)前文檔Ruff: Organize Imports- 排序?qū)胝Z句
4.3 與 Black 的遷移
如果之前使用 Black,確保禁用 Black 并切換到 Ruff:
{
"python.formatting.provider": "none",
"[python]": {
"editor.defaultFormatter": "charliermarsh.ruff"
}
}
5. 常見問題解決
5.1 擴(kuò)展安裝后無反應(yīng)
問題:安裝后沒有代碼檢查或格式化功能
解決方案:
- 檢查 Ruff 版本:
ruff --version(建議 ≥ 0.5.3) - 確保 Python 擴(kuò)展已安裝
- 檢查 Python 解釋器選擇是否正確(按
Ctrl+Shift+P→ “Python: Select Interpreter”) - 查看輸出面板:終端 → 輸出 → 選擇 “Ruff” 查看日志
5.2 與 Pyright 類型檢查沖突
問題:Ruff 和 Pyright 同時(shí)運(yùn)行導(dǎo)致重復(fù)提示
解決方案:
{
"python.analysis.diagnosticSeverityOverrides": {
"reportMissingImports": "none",
"reportUnusedVariable": "none"
}
}
5.3 格式化與 Black 不一致
問題:團(tuán)隊(duì)同時(shí)使用 Black 和 Ruff 導(dǎo)致格式?jīng)_突
解決方案:
- 在
pyproject.toml中配置 Ruff 的 Black 兼容模式:
[tool.ruff.format] # Ruff 默認(rèn)就是 Black 兼容的,無需特殊配置 preview = true # 啟用最新的 Black 兼容特性
5.4 性能問題(大文件卡頓)
解決方案:
{
"ruff.lint.run": "onType", // 改為 onSave 減少實(shí)時(shí)檢查
"files.watcherExclude": {
"**/.ruff_cache/**": true
}
}
6. 調(diào)試和日志
啟用詳細(xì)日志
在 settings.json 中:
{
"ruff.logLevel": "debug",
"ruff.trace.server": "verbose",
"ruff.logFile": "${workspaceFolder}/.vscode/ruff.log"
}
檢查 Ruff 配置
在終端運(yùn)行:
# 檢查當(dāng)前配置 ruff check --show-settings # 檢查格式化配置 ruff format --show-settings
7. 版本要求和建議
| 組件 | 最低版本 | 推薦版本 |
|---|---|---|
| VSCode | 1.74.0 | 1.80.0+ |
| Ruff 擴(kuò)展 | 2024.32.0 | 最新版 |
| Ruff CLI | 0.5.3 | 0.9.8+ |
| Python | 3.7 | 3.10+ |
建議定期更新:
# 更新 Ruff CLI pip install --upgrade ruff # 更新 VSCode 擴(kuò)展 # 在擴(kuò)展面板點(diǎn)擊更新按鈕
8. 完整配置示例
推薦的生產(chǎn)環(huán)境配置
// .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 中提供流暢的代碼檢查和格式化體驗(yàn),大幅提升 Python 開發(fā)效率。
到此這篇關(guān)于Python中Ruff使用指南的文章就介紹到這了,更多相關(guān)Python Ruff使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- python代碼檢查工具pylint 讓你的python更規(guī)范
- python中pylint使用方法(pylint代碼檢查)
- python設(shè)置檢查點(diǎn)簡單實(shí)現(xiàn)代碼
- 使用pycharm和pylint檢查python代碼規(guī)范操作
- Python中使用md5sum檢查目錄中相同文件代碼分享
- 21行Python代碼實(shí)現(xiàn)拼寫檢查器
- 使用Python編寫文件重復(fù)檢查器的完整代碼
- 利用python檢查磁盤空間使用情況的代碼實(shí)現(xiàn)
- Python?調(diào)用函數(shù)時(shí)檢查參數(shù)的類型是否合規(guī)的實(shí)現(xiàn)代碼
- Python庫coala代碼分析和自動(dòng)化檢查改進(jìn)工具使用探索
基于pytorch實(shí)現(xiàn)運(yùn)動(dòng)鞋品牌識別功能
使用Python實(shí)現(xiàn)Flutter項(xiàng)目的自動(dòng)化構(gòu)建與發(fā)布
Python多進(jìn)程入門、分布式進(jìn)程數(shù)據(jù)共享實(shí)例詳解
Python腳本實(shí)現(xiàn)Zabbix多行日志監(jiān)控過程解析
Python通過解析網(wǎng)頁實(shí)現(xiàn)看報(bào)程序的方法

