Recommended way to install multiple Python versions on Ubuntu 20.04

Ubuntu 20.04 comes with Python 3.8 pre-installed. However, you may want to install other Python versions. In this tutorial, I will show you the recommended way to install latest Python version on Ubuntu 20.04.

The tool we will use is called pyenv. pyenv is a tool that helps us manage multiple versions of Python. pyenv lets you easily switch between multiple versions of Python. It's simple, unobtrusive, and follows the UNIX tradition of single-purpose tools that do one thing well.

Install dependencies #

For pyenv to work properly, you need to install required dependencies.

Open a terminal and type the following command:

sudo apt-get update; sudo apt-get install make build-essential libssl-dev zlib1g-dev \
libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm \
libncursesw5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev

Install pyenv #

Install pyenv by typing the following command:

curl https://pyenv.run | bash

Restart your shell so the path changes take effect:

exec $SHELL

Check if pyenv is installed successfully:

pyenv -v

Install/Unstiall Python with pyenv #

The pyenv install is used to install Python version. Its syntax is:

Usage: pyenv install [-f] [-kvp] <version>
       pyenv install [-f] [-kvp] <definition-file>
       pyenv install -l|--list

  -l/--list             List all available versions
  -f/--force            Install even if the version appears to be installed already
  -s/--skip-existing    Skip the installation if the version appears to be installed already

  python-build options:

  -k/--keep        Keep source tree in $PYENV_BUILD_ROOT after installation
                   (defaults to $PYENV_ROOT/sources)
  -v/--verbose     Verbose mode: print compilation status to stdout
  -p/--patch       Apply a patch from stdin before building
  -g/--debug       Build a debug version

For example to install Python 3.9.6, type the following command:

pyenv install 3.9.6

To activate the Python 3.9.6 globally, type the following command:

pyenv global 3.9.6

The syntax for unstall a specific Python version is:

Usage: pyenv uninstall [-f|--force] <version>

   -f  Attempt to remove the specified version without prompting
       for confirmation. If the version does not exist, do not
       display an error message.

To uninstall Python 3.9.6, type the following command:

pyenv uninstall 3.9.6

You can install multiple versions of Python at the same time by using the pyenv install command. For example, to install Python 3.8.5 and 3.9.6, type the following command:

pyenv install 3.8.5 3.9.6

You of course can keep multiple Python versions.

For more information about pyenv, please visit pyenv repository

Tags:

Python

Linux