You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Neovim中Python LSP客户端(Pyright)无法附着缓冲区求助

解决Pyright无法附着Python缓冲区的问题

核心问题定位

日志中的Cannot find module 'worker_threads'是关键——Pyright依赖Node.js的worker_threads模块,该模块在Node.js 10.5.0之后才稳定支持,而Pyright官方要求Node.js 16.10.0或更高版本,你的系统当前Node版本不满足要求,导致Pyright启动失败。同时:LspInfo显示Pyright未找到项目根目录,这也会影响自动附着逻辑。


步骤1:更新Linux Mint上的Node.js

Linux Mint默认软件源的Node版本普遍偏旧,推荐用nvm(Node版本管理器)安装高版本Node:

  1. 克隆nvm仓库到本地:
    git clone https://github.com/nvm-sh/nvm.git ~/.nvm
    
  2. 将nvm环境变量添加到shell配置文件(以bash为例):
    echo 'export NVM_DIR="$HOME/.nvm"' >> ~/.bashrc
    echo '[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"' >> ~/.bashrc
    echo '[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"' >> ~/.bashrc
    
  3. 重新加载shell配置:
    source ~/.bashrc
    
  4. 安装并启用Node.js 20.x(长期支持版):
    nvm install 20
    nvm use 20
    
  5. 设置默认Node版本,避免重启shell后失效:
    nvm alias default 20
    

验证版本:

node --version

输出应为v20.x.x即可。


步骤2:修复Pyright根目录检测问题

Pyright需要识别项目根目录下的pyproject.toml、setup.py、requirements.txt或.git等标记文件,否则会无法自动附着。

临时强制附着(单文件场景)

打开目标.py文件后,执行以下Vim命令强制启动Pyright并完成附着:

:lua vim.lsp.start({
  name = 'pyright',
  cmd = {'~/.local/share/nvim/mason/bin/pyright-langserver', '--stdio'},
  root_dir = vim.fn.getcwd(),
  settings = {
    python = {
      analysis = {
        autoSearchPaths = true,
        useLibraryCodeForTypes = true
      }
    }
  }
})

此命令将当前工作目录设为Pyright的根目录,绕过自动检测逻辑强制附着。

长期配置(项目场景)

在你的Neovim Lua配置中,修改mason-lspconfig的Pyright配置,扩展根目录检测规则:

require('mason-lspconfig').setup_handlers({
  -- 通用LSP配置
  function(server_name)
    require('lspconfig')[server_name].setup({
      -- 你的通用配置(如快捷键、on_attach逻辑等)
    })
  end,
  -- Pyright专属配置
  pyright = function()
    require('lspconfig').pyright.setup({
      root_dir = require('lspconfig.util').root_pattern(
        '.git', 
        'pyproject.toml', 
        'setup.py', 
        'requirements.txt',
        '.pyrightconfig' -- 可自定义项目标记文件
      ),
    })
  end
})

步骤3:验证修复

  1. 重启Neovim,打开.py文件,执行:LspInfo,检查Pyright是否出现在“attached to this buffer”列表中。
  2. 查看日志确认无报错:
    cat ~/.local/state/nvim/lsp.log
    

内容的提问来源于stack exchange,提问作者loz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 00:27:47