ruff-formatter

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Ruff Formatter

Ruff 格式化工具

Fast Python code formatter, drop-in replacement for Black with >99.9% compatibility.
快速的Python代码格式化工具,可作为Black的直接替代品,兼容性超过99.9%。

Quick Reference

快速参考

bash
undefined
bash
undefined

Format 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 .
undefined
ruff format --diff .
undefined

Fixing Formatting Issues

修复格式问题

When
ruff format --check
fails:
  1. Run
    ruff format .
    to auto-fix all formatting
  2. Review changes with
    git diff
  3. 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
执行失败时:
  1. 运行
    ruff format .
    自动修复所有格式问题
  2. 使用
    git diff
    查看更改内容
  3. 提交格式化后的代码
对于导入排序问题,请先运行检查工具:
bash
ruff check --select I --fix .  # 排序导入语句
ruff format .                   # 然后进行格式化

Format Suppression

格式抑制

Disable formatting for specific code:
python
undefined
禁用特定代码的格式化:
python
undefined

fmt: 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
undefined
x = 1 # fmt: skip
undefined

Configuration

配置

In
pyproject.toml
or
ruff.toml
:
toml
[tool.ruff.format]
quote-style = "double"      # or "single"
indent-style = "space"      # or "tab"
line-length = 88            # default
docstring-code-format = true
pyproject.toml
ruff.toml
中配置:
toml
[tool.ruff.format]
quote-style = "double"      # 或 "single"
indent-style = "space"      # 或 "tab"
line-length = 88            # 默认值
docstring-code-format = true

Exit Codes

退出码

  • 0: Success (files formatted or already formatted)
  • 1: With
    --check
    : files need formatting
  • 2: Error (invalid config, CLI error)
  • 0:成功(文件已格式化或无需格式化)
  • 1:使用
    --check
    时:文件需要格式化
  • 2:错误(无效配置、CLI错误)