使用 Neovim 进行 Python 开发
本文仅以 Windows 下的 LazyVim 配置环境为例。
启用 Python 支持
可启用 LazyVim 自带的 Python 语言插件。在 %LOCALAPPDATA%\nvim\lua\config\lazy.lua
文件中加入以下高亮代码:
lua -- import any extras modules here
{ import = "lazyvim.plugins.extras.lang.python" },
-- { import = "lazyvim.plugins.extras.lang.typescript" },
-- { import = "lazyvim.plugins.extras.lang.json" },
-- { import = "lazyvim.plugins.extras.ui.mini-animate" },
选择 Virtualenv
当 Neovim 打开一个 Python 项目时,默认会加载项目根目录下的 venv 路径下的 Virtualenv 。可以使用 venv-selector.nvim
插件为当前项目选择指定的 Virtualenv 。使用命令 :VenvSelect
或者快捷键 <leader>cv
打开 Virtualenv 选择窗口。不过默认只能识别出 venv 目录中的 Virtualenv ,可以进行配置来支持其他目录名称。
创建配置文件 %LOCALAPPDATA%\nvim\lua\plugins\python.lua
,写入内容:
luareturn {
{
"linux-cultist/venv-selector.nvim",
opts = {
-- 支持在 venv 和 .venv 目录名中查找 Python Virtualenv
name = {'venv', '.venv'},
auto_refresh = true,
},
},
}
此外,还可以为每个项目进行单独配置。
在项目根目录下创建 pyright 的配置文件 pyrightconfig.json
,下面的代码用于指定当前项目的 Virtualenv 目录:
json{
"venvPath": ".",
"venv": ".venv"
}
或者在项目 pyproject.toml
文件中进行配置:
toml[tool.pyright]
venvPath = "."
venv = ".venv"
更多 pyright 的配置项可以参考: https://microsoft.github.io/pyright/#/configuration
代码检查
LazyVim 默认配置使用 Ruff 作为代码检查器。使用快捷键 <leader>ca
打开 Code actions 窗口,可以看到 Ruff 提供的代码操作选项。主要提供代码自动修复和 Import 顺序优化功能。
可以在项目根目录中创建 ruff.toml
文件,或者将配置写入 pyproject.toml
文件的 [tool.ruff]
小结中,两者等价。比如要设置每行最长字数为 120 字,可以编辑 pyproject.toml
文件,添加如下内容:
toml[tool.ruff]
line-length = 120
更多 Ruff 的配置项可以参考: https://beta.ruff.rs/docs/settings/
nvim-lsconfig
命令
:LspInfo
shows the status of active and configured language servers.:LspStart <config_name>
Start the requested server name. Will only successfully start if the command detects a root directory matching the current config. Passautostart = false
to your.setup{}
call for a language server if you would like to launch clients solely with this command. Defaults to all servers matching current buffer filetype.:LspStop <client_id>
Defaults to stopping all buffer clients.:LspRestart <client_id>
Defaults to restarting all buffer clients.