When using Ubuntu in WSL you need to be careful about upgrading Python to something newer (for 20.04 LTS the default is Python 3.8) as it may affect system operations.

One solution I found keeps the system running with Python 3.8, and allows you to run Python 3.9 in a virtual environment.

  1. Python 3.9 is currently available in the main Ubuntu repositories, so we'll simply use apt to install it. First update apt with:
    sudo apt update
  2. Then install the relevant packages. I've included a couple of extras here to help later on:
    sudo apt install python3.9 python3.9-venv
  3. Once the packages are installed, let's setup the virtual environment (venv). Firstly create the venv & path:
    user@machine:~$ python3.9 -m venv /home/username/.venvs/<name of venv>

    For my own clarity, and a basic environment, i've simply called mine py3_9. Also in the command below, i've truncated the path to my homedir using the ~ character:

    user@machine:~$ python3.9 -m venv ~/.venvs/py3_9
  4. Now enter the venv:
    user@machine:~$ source ~/.venvs/py3_9/bin/activate
  5. Straight away you should notice the prompt has now changed to reflect the `venv , the name of which will now precede the rest of the path:
    (py3_9) user@machine:~$
  6. You can now check the version of python that is running with:
    (py3_9) user@machine:~$ python -V
    Python 3.9.5
  7. Best to install a newer version of pip as well:
    (py3_9) user@machine:~$ wget http://bootstrap.pypa.io/get-pip.py
    (py3_9) user@machine:~$ python get-pip.py
  8. And then confirm the version of pip3:
    (py3_9) user@machine:~$ pip3 --version
    pip 22.2.2 from /home/username/.venvs/py3_9/lib/python3.9/site-packages/pip (python 3.9)
  9. When done, exit the venv with:
    (py3_9) user@machine:~$ deactivate

Refs:

Previous Post

Add a comment