Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set python interpreter in neovim for python language server depending on pyenv / virtualenv

I am using the pyright LSP in neovim (0.5). It works, but seems to only pick up on packages available in the standard python installation. It does not autocomplete for packages not in the base python, but in my pyenv environment. In VSCode this is quite easily done by selecting the interpreter.

How can I set the virtual environment or pyenv version to be used by Pyright LSP in Neovim?

like image 754
Mike Avatar asked Dec 02 '25 10:12

Mike


1 Answers

This is not actually an answer, there is this issue in nvim-lsp where they explore some alternatives, it turns out nvim (or pyright, I don't know exactly) don't respect/load pyenv local .python-version file. An alternative is to use regular venv. Using pyenv shell myvenv before running nvim also works, but it goes against the convenience of .python-version file. Maybe there is a way to load the correct venv with some scripts in bashrc/zshrc/config.fish, but again this is not that convenient, IMHO.

https://github.com/neovim/nvim-lspconfig/issues/717

EDIT: Found a good solution

There is a simple way to get pyright work with pyenv virtualenvs:

Create pyrightconfig.json file in root directory of your project, and paste the following, relacing USERNAME and MY-VENV with your user and venv, supposing your pyenv is installed in ~/.pyenv. It adds another file beyond .python-version, but its easy and don't mess with your shell configs.

{
    "venvPath": "/home/USERNAME/.pyenv/versions/",
    "venv": "MY-VENV"
}

You can check full doc here: https://github.com/microsoft/pyright/blob/master/docs/configuration.md

EDIT 2: Checkout this plugin pyenv-pyright I created. With it you can setup pyright to use pyenv venvs with only one command:

pyenv local my-venv
pyenv pyright

or

pyenv pyright my-venv

This will automatically create/update pyrightconfig.json file with the pyenv virtualenv of your choice. Its a convenient way to overcome neovim+pyright+pyenv virtualenvs setup. https://github.com/alefpereira/pyenv-pyright

like image 161
Alef Pereira Avatar answered Dec 07 '25 05:12

Alef Pereira