How to install latest version of python 3.9.5 on Ubuntu 20.04?

Solution 1:

You can run python3.9 with the command

python3.9

(instead of the command python or python3)

It is a good idea not to change the default version of python3 to python3.9, as that may break your Ubuntu installation. Instead, manually call it with python3.9.

Solution 2:

In addition to explicitly specifying the python3.9 and working with it globally as explained in Archisman Panigrahi answer ... You can create an isolated virtual environment where python3 -V will report Python 3.9.

This feature can be installed for Python3 like so:

sudo apt install python3-venv

To make a Python3.9 virtual environment, you would first create a directory and cd to it like so:

mkdir my_env && cd my_env

Then, create a new Python3.9 virtual environment inside the directory like so:

python3.9 -m venv env

To use this environment, activate it like so:

source env/bin/activate

Your shell prompt will show (env) like so:

(env) $

During this, python3 -V will report Python 3.9 and commands, module installs or modifications will be contained locally in this virtual environment.

When you are done, deactivate this Python3.9 virtual environment like so:

deactivate

Solution 3:

Consider installing Python with Anaconda or Miniconda (I recommend Miniconda). Conda lets you manage different Python versions easily with virtual environments.

sudo wget -c https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh

sudo chmod +x Miniconda3-latest-Linux-x86_64.sh

./Miniconda3-latest-Linux-x86_64.sh

Press enter until it asks for "yes" or "no", then type "yes" to accept the terms of use.

If you're using a shell other than bash, type:

conda init <SHELL_NAME> (Supported shells include: fish, tcsh, xonsh, zsh)

Close and open the terminal. Type conda activate to activate the (base) conda environment.

Create a Python 3.9.5 environment, and name it whatever you like:

conda create -n myenv python=3.9.5

Once created, you can activate and use that Python environment:

conda activate myenv

When finished, you can deactivate your environment with:

conda deactivate

Any packages you install with pip or conda will be local to whatever environment you're using, so you don't have to worry about package conflicts. Just don't install everything in your (base) environment, because anything installed in (base) will get copied to new conda environments you create.

Sources:

Setting up Miniconda on Ubuntu

Conda Cheat Sheet

Anaconda Docs