Ruff 是一个用 Rust 编写的极快速的 Python 代码检查工具和格式化工具,可以替代 Flake8、Black、isort 等工具,同时执行速度更快。

设置 Ruff 的 Visual Studio Code 扩展主要涉及配置文件和 VS Code 的设置。以下是详细的步骤和说明:

1. 安装 Ruff 扩展

  1. 打开 Visual Studio Code。
  2. 点击左侧的扩展图标(四边形拼图图标)。
  3. 在搜索框中输入 Ruff
  4. 找到 Ruff 扩展(由 charliermarsh 提供),点击“安装”按钮。

2. 安装 Ruff 本身

Ruff 扩展需要本地安装 Ruff 工具。可以通过以下命令安装:

pip install ruff

3. 配置 Ruff

Ruff 的配置可以通过 pyproject.tomlruff.toml.ruff.toml 文件进行。以下是一个示例 pyproject.toml 文件:

[tool.ruff]
line-length = 88
select = ["C", "E", "F", "W"]
ignore = ["E501"]
extend-select = ["I"]
  • line-length:设置最大行长度。
  • select:启用的规则集。
  • ignore:忽略的规则。
  • extend-select:扩展的规则集,例如 I 表示启用 isort 规则。

将此文件放在项目的根目录下,Ruff 会自动加载配置。

4. 配置 VS Code 设置

你可以在 VS Code 的 settings.json 文件中配置 Ruff。以下是一些常见的配置:

4.1 格式化代码

确保在保存时格式化代码:

{
  "[python]": {
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "charliermarsh.ruff"
  }
}
4.2 修复违规

确保在保存时修复可自动修复的违规:

{
  "[python]": {
    "editor.codeActionsOnSave": {
      "source.fixAll": "explicit"
    }
  }
}
4.3 整理导入

确保在保存时整理导入:

{
  "[python]": {
    "editor.codeActionsOnSave": {
      "source.organizeImports": "explicit"
    }
  }
}
4.4 启用 Rust-based Language Server

确保使用 Rust-based Language Server(推荐):

{
  "ruff.nativeServer": "on"
}
4.5 指定 Ruff 配置文件

如果需要指定自定义的 Ruff 配置文件路径:

{
  "ruff.configuration": "/path/to/ruff.toml"
}
4.6 设置日志级别

设置 Ruff 的日志级别:

{
  "ruff.logLevel": "info"
}
4.7 指定日志文件

将 Ruff 的日志输出到文件:

{
  "ruff.logFile": "/path/to/ruff.log"
}
4.8 捕获 LSP 消息

捕获 Ruff 语言服务器与编辑器之间的 LSP 消息:

{
  "ruff.trace.server": "messages"
}

5. 配置 Jupyter Notebook

如果你使用 Jupyter Notebook,可以添加以下配置:

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

6. 使用命令

Ruff 扩展提供了以下命令,可以通过 VS Code 的命令面板(Ctrl+Shift+PCmd+Shift+P)访问:

  • Ruff: Fix all auto-fixable problems:修复所有可自动修复的问题。
  • Ruff: Format Imports:整理导入。
  • Ruff: Format Document:格式化整个文档。
  • Ruff: Restart Server:强制重启语言服务器。
  • Ruff: Print debug information (native server only):打印调试信息。
  • Ruff: Show client logs:打开 Ruff 输出通道。
  • Ruff: Show server logs:打开 Ruff 语言服务器输出通道。

7. 验证配置

  1. 打开一个 Python 文件或 Jupyter Notebook。
  2. 保存文件,检查是否自动格式化、修复违规和整理导入。
  3. 如果需要,可以手动运行上述命令验证功能。

完整的配置示例

{
  "[python]": {
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "charliermarsh.ruff",
    "editor.codeActionsOnSave": {
      "source.fixAll": "explicit",
      "source.organizeImports": "explicit"
    }
  },
  "notebook.formatOnSave.enabled": true,
  "notebook.codeActionsOnSave": {
    "notebook.source.fixAll": "explicit",
    "notebook.source.organizeImports": "explicit"
  },
  "ruff.nativeServer": "on",
  "ruff.logLevel": "info",
  "ruff.logFile": "/path/to/ruff.log",
  "ruff.trace.server": "messages",
  "ruff.lineLength": 88  // 设置代码行长度为 88
}
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐