0. Major Edit: Add to .bashrc
To automate activation of .venv
1. Problem: Wrong Python Interpreter
When opening a project, VS-Code keeps opening some previous Interpreter or the wrong one compared. The required one is simply the one in the local .venv
folder.
And terminal shows this:
1.1 Terminal Meaning: fapi(.venv)
Two sections:
interpreter
(virtual environment)
What is happening:
- VSC is using the Python interpreter:
fapi...
,- it’s the first interpreter it find its in path or
- more likely, we previously selected this interpreter and forgot we did.
- VSC automatically prefixs interpreters name (part of it) to our terminal, simply to inform us.
- VSC is also automatically activating local
.venv
and appends to terminal.
2. Solution 1 via Manually GUI
Choose from menu:
Select Interpreter
[GUI via Ctrl + Shift + P]:- Choose local .venv:
('.venv') ./.venv/bin/python
- Choose local .venv:
This will start a process to update 3 areas:
- [1]: Highlights the selected interpreter if you go back to
Select Interpreter
[GUI via Ctrl + Shift + P] - [2]: Interpreter Prefix now updates from
fapi
(in Section 1.1 Meaning) to selected local interpreter.venv
in [1] - [3]: Shows selected local interpreter
.venv
- [4]: No defaults (see Solution 2)
3. Solution 2: Create .vscode/settings.json
3.1 Solution 2 Part 1: Add key-value pair
Add default interpreter
.vscode/settings.json
file:{ "python.defaultInterpreterPath": "${workspaceFolder}/.venv/bin/python" }
3.2 Solution 2 Part 1: Reset Workspace Settings
Okay so this also requires using the GUI but I’m sure theres a way to automate this too…
- Choose from menu (via Ctrl + Shift + P):
Clear Workspace Interpreter Setting
Step 4: Confirm Okay
A few things to notice: - [1] VS-Code default in menu is now always the .venv
’s python, which wasn’t available doing it manually - [1] VS-Code automatically chose it (after you settings reset) - [2] No errors finding interepreter (see next section when interpreter cant be found) - [3] Shows seleted interpreter
Step 5: Problems & Debugging
If path provided to settings.json
is incorrect, (e.g. I made up a mate/.venv
which doesnt exist)
- [1]: VSC shows default path but it doesnt actually exist
- [2]: VSC stuck in infinite loop looking for it
- [3]: VSC cant find it, will just show Python rather than a particular interpreter
Reference: https://code.visualstudio.com/docs/python/settings-reference#_general-python-settings
Summary:
- VSC stores your last selection in:
Python: Select Interpreter (Ctrl + Shift + P)
- Reset workspace settings to start afresh in menu.
- Explicity set a default interpreter
.venv
insettings.json
. - If our venv is named exactly
.venv
, VSC will also automatically activate it upon opening VSC.