Background:
In WSL2 (ubuntu 20.04) I created a python virtual environment inside a directory. Using the command python3 -m venv venv
my system's python version was set to python3.11 (after downloading) via sudo update-alternatives --config python3
and then choosing the version. I noticed I was having some errors of missing modules when I started WSL2 (happening after a computer restart), I read this was because I was using a different python version than the one ubuntu 20.04 came with so I switched back to 3.8 via the config menu as before. I am also using VS code that's connected to my WSL2.
These are some of the contents of my venv directory: venv/bin/python
venv/bin/python3
venv/bin/python3.11
venv/bin/pip
venv/bin/pip3
Question:
After activating my virutal env via source venv/bin/activate
, when I do python3 --version
I still get a version of 3.8.10 despite creating the virtual environment with 3.11. I was able to get the interpretor set to 3.11 on VS code.I know I was in the virtual environment since my command prompt had (venv) in front. I went into the python console while in the virtual env and did import sys
and sys.path
this was my output ['', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload']
. Why isn't the python version changing, am I misunderstanding something or did I not do something correctly? Seems like pip isn't working either but works when I switch my system python to 3.11 (I tried installing it on 3.8 but it said it was already installed).
Solved:
Answered below, just re-created the virtual env while making sure my system python version was 3.11 (may have been some mixup earlier).
CodePudding user response:
By changing the selection in sudo update-alternatives --config python3
you change the selected python version also for the chosen vitrual environment (at least when using venv
, it might be different with other tools).
That can cause issues, because when creating a new virtual environment envname
using venv
from a specific python version xx.xx
, a directory named pythonxx.xx
is created in /envname/lib/
, and inside it a directory named site-packages
that contains the packages installed by the pip
of this specific environment.
So changing back to the original python version of the environment through sudo update-alternatives --config python3
should solve the issue, and probably the errors of missing modules are due to the incompatibility of the current selected python version with the original version which you installed the virtual environment from.
Personally, to avoid confusing, I name my virtual environments with the python version as a suffix, e.g envname_py3.11.1
. But there might be a better method which I am not aware of.
CodePudding user response:
I deleted my venv directory and recreated my virtual environment while on python3.11. This has resolved my issue.