Skip to content
Advertisement

use different python version (3.8) and virtual environment in VSC workspace (sub)folder only

I would like to use a different version of Python (3.8.0) and a dedicated virtual environment in a subfolder of a VSC project/work space. Is this possible? Any pointers would be very much appreciated. Thus far U tried to follow this using pyenv.

I ran:

pyenv local 3.8.0
python -m venv .venv
..venvScriptsactivate

in the VSC terminal but when I run:

(.venv) PS C:blaproject> python -V

I still get:

Python 3.10.4

Is there a step I missed? There is a .python-version file containing 3.8.0 but ..venvScriptsactivate does not seem to use this and stick, in my case, with Python 3.10.4?

Advertisement

Answer

The lower right corner of VS code will display the current interpreter version.

enter image description here

Then, we need to understand one thing, the terminal in VS code uses the built-in powershell of Windows, so when you use the python -m venv .venv command in the VS code terminal to create a new virtual environment, the python at this time points to the python version configured by the environment variable in your machine. Same as you use python command in external cmd window or poweshell.

For example, at this time, my Windows environment variable is configured with the path of python310

enter image description here

then I use the python -m venv .venv310 command in the vscode terminal to create a new virtual environment, and the python version of the virtual environment is 3.10.4.

enter image description here

If you need to use other versions, you can modify the windows environment variables, or you can directly specify the path of the python version in the command.

For example, I use the following command to specify the python3.9 version to create a new virtual environment,

C:UsersAdminanaconda3python.exe -m venv .venv39

enter image description here

PS: Click the interpreter version in the lower right corner to choose to switch between different interpreters.

enter image description here

After switching, you can create a new terminal to activate the environment.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement