Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto-switching Python Virtual Environments in Visual Studio Code per Directory within a Workspace

I am working on a project in VSCode that has multiple directories, each of which requires a different Python virtual environment. My virtual environments are located in the ~/.virtualenvs directory and my workspace is structured like this:

~/.virtualenvs/
│
├── venv_A/
│
└── venv_B/

my_workspace/
│
├── project_A/
│   └── script_A.py
│
└── project_B/
    └── script_B.py

I want VSCode to automatically switch to the appropriate virtual environment (venv_A for project_A, and venv_B for project_B) located in ~/.virtualenvs when I open a Python file from each directory within the workspace. Currently, I have to manually select the virtual environment through the command palette each time.

I have tried looking through the VSCode documentation and searched for guides or tutorials on how to achieve this functionality, but I haven't found anything that addresses this specific issue. I expected there to be some configuration options either through the .vscode/settings.json file or the workspace settings that would allow me to specify which virtual environment should be used for each directory, and how Pylance, pylint, and yapf should adapt accordingly.

I am aware that VSCode has support for workspaces and .env files, but I'm not sure how to configure it to auto-switch virtual environments based on the directory, and to have Pylance, pylint, and yapf adapt accordingly.

I also found the issue Select pyenv environment based on folder .python-version file that is not closed.

like image 849
Vi1i Avatar asked Oct 19 '25 06:10

Vi1i


1 Answers

The easiest way is to open project_A and project_B as workspaces respectively, and then select an interpreter for the workspace, vscode will remember your choice, and will still use the previously selected interpreter when it is opened next time.

Another approach is to use Multi-root Workspaces

  • Open a new window and use Add Folder to Worspace... to add both folders to the current workspace,

    enter image description here enter image description here

  • Then created separate virtual environments for both folders using Ctrl+Shift+P --> Python: Create Environment... and select the interpreter for the respective folder.

    enter image description here

    You can also select the .py file in the corresponding folder, and then click the python version in the lower right corner to switch

These documents may also be useful:

  • https://code.visualstudio.com/docs/python/python-tutorial#_select-a-python-interpreter

  • https://code.visualstudio.com/docs/python/environments#_working-with-python-interpreters

  • https://code.visualstudio.com/docs/editor/profiles

like image 187
JialeDu Avatar answered Oct 21 '25 20:10

JialeDu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!