ruff-formatter
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseRuff Formatter
Ruff 格式化工具
Fast Python code formatter, drop-in replacement for Black with >99.9% compatibility.
快速的Python代码格式化工具,可作为Black的直接替代品,兼容性超过99.9%。
Quick Reference
快速参考
bash
undefinedbash
undefinedFormat all files in current directory
格式化当前目录下的所有文件
ruff format .
ruff format .
Format specific file(s)
格式化特定文件
ruff format path/to/file.py
ruff format path/to/file.py
Check without modifying (CI/pre-commit)
检查格式但不修改文件(适用于CI/预提交)
ruff format --check .
ruff format --check .
Show diff of what would change
显示将要做出的更改差异
ruff format --diff .
undefinedruff format --diff .
undefinedFixing Formatting Issues
修复格式问题
When fails:
ruff format --check- Run to auto-fix all formatting
ruff format . - Review changes with
git diff - Commit the formatted code
For import sorting issues, run linter first:
bash
ruff check --select I --fix . # Sort imports
ruff format . # Then format当执行失败时:
ruff format --check- 运行自动修复所有格式问题
ruff format . - 使用查看更改内容
git diff - 提交格式化后的代码
对于导入排序问题,请先运行检查工具:
bash
ruff check --select I --fix . # 排序导入语句
ruff format . # 然后进行格式化Format Suppression
格式抑制
Disable formatting for specific code:
python
undefined禁用特定代码的格式化:
python
undefinedfmt: off
fmt: off
matrix = [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
]
matrix = [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
]
fmt: on
fmt: on
x = 1 # fmt: skip
undefinedx = 1 # fmt: skip
undefinedConfiguration
配置
In or :
pyproject.tomlruff.tomltoml
[tool.ruff.format]
quote-style = "double" # or "single"
indent-style = "space" # or "tab"
line-length = 88 # default
docstring-code-format = true在或中配置:
pyproject.tomlruff.tomltoml
[tool.ruff.format]
quote-style = "double" # 或 "single"
indent-style = "space" # 或 "tab"
line-length = 88 # 默认值
docstring-code-format = trueExit Codes
退出码
- 0: Success (files formatted or already formatted)
- 1: With : files need formatting
--check - 2: Error (invalid config, CLI error)
- 0:成功(文件已格式化或无需格式化)
- 1:使用时:文件需要格式化
--check - 2:错误(无效配置、CLI错误)