0

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
.\.venv\Scripts\activate

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 ..venv\Scripts\activate does not seem to use this and stick, in my case, with Python 3.10.4?

cs0815
  • 16,751
  • 45
  • 136
  • 299

1 Answers1

1

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:\Users\Admin\anaconda3\python.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.

JialeDu
  • 6,021
  • 2
  • 5
  • 24
  • thanks for this amazing and exhausting post. so are you saying I could have an older version of Python (3.8) installed "quietly" and can run C:\bla\python.exe -m venv .venv3.8 and do not need pyenv? – cs0815 Sep 15 '22 at 08:53
  • Sorry for confusing you with my answer. Where do you have questions? If you want to create a virtual environment of `python3.8`, that's what you said `C:\bla\python.exe -m venv .venv3.8`. – JialeDu Sep 15 '22 at 08:58
  • so is there no need for pyenv? – cs0815 Sep 15 '22 at 09:30
  • no need. Did you try it? Maybe run it and you will know if you need it or not. – JialeDu Sep 15 '22 at 09:39
  • `.venv39` is simply a folder name and has nothing to do with versioning. `python -V` will tell you the version that venv will create. The fact that you have 5+ versions of Python in your AppData folder is a bit concerning – OneCricketeer Mar 12 '23 at 16:17