NOTE: Recently switched back to using pyenv so I can run multiple python versions without losing my mind. It only takes a few minutes to set up, but provides the flexibility I need without making things too complicated. See my gist, Manage python versions on Linux with pyenv for more.
The deadsnakes PPA make the latest stable versions of python available on Ubuntu 18.04 LTS (3.9 is already in the official apt repo for 20.04). I now find it preferable to installing from source.
The following was tested on a Ubuntu 18.04.5 LTS desktop with python 3.6.9 as the system python version ("python3").
The latest python available from deadsnakes as of July, 2021 is 3.9.6.
On Ubuntu, be sure you have the build-essential
meta package installed. It's a prerequisite for any modules that need compiling.
$ sudo apt install build-essential
- First, add the deadsnakes PPA to apt:
$ sudo add-apt-repository ppa:deadsnakes/ppa
- Next, do the usual update and upgrade:
$ sudo apt update && sudo apt upgrade
(if the result looks good to you, go ahead and answer "y" to do the upgrade)
- Then install the basic python3.9 packages:
$ sudo apt install python3.9 python3.9-dev python3.9-venv
This will install the python3.9 binary to /usr/bin.
- Make sure the associated pip is installed for your user environment:
$ python3.9 -m ensurepip --default-pip --user
- Fire up python3.9 to verify the install:
$ python3.9
Python 3.9.6 (default, Jul 3 2021, 17:50:42)
[GCC 7.5.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> quit()
- Finally, make sure you can create a virtual environment:
$ cd testing
$ python3.9 -m venv venv
$ source venv/bin/activate
(venv) $ python --version
Python 3.9.6
(venv) $
One of the key reasons this works for me is that I've been aggressive about individually virtualizing project environments with venv.
I've trained myself to never to use sudo to when doing a "pip install", because there lies the road to ruin.
Once I've gone through the steps above I first test pip by trying to upgrade it with the "--user" flag:
$ python3.9 -m pip install --upgrade pip --user
The next thing I do is install ipython. Just because.
$ pip install ipython --user
From that point forward I try to minimize the packages I add to my base user environment, and try to regularly generate a requirements.txt (pip freeze >requirements.txt
) to keep track of things. Each of my development projects has their own virtual environment created with venv.