Build Python 3.7 from Source

In this tutorial, we will see how to build customized python version from source on Ubuntu and how to install this customized python version in our local system.

We will see several install options - install as main python interpreter, install it as alternative python interpreter. The last option is creating and installing a deb package with the help of checkinstall - This allows easily remove the package with one step and to install the resulting package upon multiple machines.

Install Build Tools

Install build tools
 # sudo apt update
 # sudo apt -y install build-essential checkinstall

Install Development Libraries

Install development libs
 # sudo apt install -y libreadline-gplv2-dev libbz2-dev libncursesw5-dev libgdbm-dev zlib1g-dev liblzma-dev libsqlite3-dev libssl-dev libffi-dev

Or select the modules you want to build and install only the relevant development libs

Module Command Notes
readline sudo apt install -y libreadline-gplv2-dev Nice to have in the interactive interpreter
bz2 sudo apt install -y libbz2-dev
curses sudo apt install -y libncursesw5-dev
dbm.gnu sudo apt install -y libgdbm-dev
gzip,zip sudo apt install -y zlib1g-dev
lzma sudo apt install -y liblzma-dev
sqlite3 sudo apt install -y libsqlite3-dev
ssl sudo apt install -y libssl-dev
tkinter sudo apt install -y tk-dev
ctypes sudo apt install -y libffi-dev use if you get : Failed to build these modules: _ctypes

Download and Extract Python Source Code

Suppose you want to build python 3.7.2:

Build python - fetch source code
 ~/# mkdir py && cd py
 ~/py# wget 
 ~/py# tar xzf Python-3.7.2.tgz && cd Python-3.7.2

Building Python

Issue the following command to build python

Build python
 ~/py/Python-3.7.2# ./configure --enable-optimizations
 ~/py/Python-3.7.2# make

If everything was OK, you can now use built python:

Build python - invoke
 ~/py/Python-3.7.2# ./python --version
 Python 3.7.2