You can configure Visual Studio Code (VS Code) to automatically use a specific virtual environment when you open a project or repository. Here’s how:
- Create or activate your virtual environment in the terminal:
python3 -m venv myenv source myenv/bin/activate # On macOS/Linux myenv\Scripts\activate # On Windows
- Install the libraries you need within this virtual environment:
pip install -r requirements.txt
-
Open the Repository in VS Code:
- Navigate to your repository in the terminal and open it in VS Code:
code .
- Navigate to your repository in the terminal and open it in VS Code:
-
Select the Python Interpreter:
- In VS Code, press
Ctrl+Shift+P
(orCmd+Shift+P
on macOS) to open the Command Palette. - Type and select Python: Select Interpreter.
- Choose the interpreter from the virtual environment you created (it will be listed by its path). It should be something like
./myenv/bin/python
.
- In VS Code, press
-
Create a Workspace Configuration (Optional):
-
To ensure VS Code uses this environment every time you open this project, you can save this setting in your workspace configuration.
-
In your project folder, create a folder called
.vscode
(if it doesn’t exist). -
Inside
.vscode
, create a file namedsettings.json
with the following contents:{ "python.pythonPath": "./myenv/bin/python" }
-
This setting ensures VS Code uses your virtual environment by default when opening the repository.
-
-
Verify the Virtual Environment:
- Open a new terminal in VS Code (
Terminal
>New Terminal
). - It should automatically activate your virtual environment and recognize the installed libraries. You can check by running:
which python # Should point to myenv/bin/python
- Open a new terminal in VS Code (
Now, every time you open this project in VS Code, it should default to using your specified virtual environment.