Python is a popular, stable, and trending programming language. Many different Linux distributions use it, including CentOS 7.
CentOS 7 by default uses Python 2.7.5, but as Python has updated to 3.9.x. , this can create challenges when you try to install most latest versions of Django or any python apps. If the default version of Python is updated, it can break base system components like the yum package manager which relies on it.
An alternate solution is to install a new Python version in parallel. In this article, we are going to see How to install Python 3 on CentOS 7 from the source. We can also use SCL (Software Collections, https://www.softwarecollections.org/en/) to install python3 but latest version available as of now is Python 3.6
How to install Python 3 on CentOS 7 from source
Start with installing updating all packages available and installing Development tools.
Don’t forget to add “sudo” before any command if you are not a root user.
# yum update -y # yum groupinstall 'Development Tools'
Make sure you have open-ssl-devel, and bzip2-devel installed as well once groupinstall is complete.
Next. browse to a directory you want to download the python source (for e.g. /usr/local/src) and download the source from https://www.python.org/ftp/python/ . At the time of writing, the latest version is 3.9.2. Copy the URL of desired python version (python-3.x.x.tgz) and download it. Here I am downloading 3.7.2
untar the package and enter the directory
tar xzf Python-3.7.2.tgz cd Python-3.7.2
Next, we will compile the source to an installation package
The make command builds the install package for python 3.7.2. As we know, the default version of python 2.7.5 already exists. So we need to install it as an alternate version in parallel. The altinstall command instructs your system to create a second installation of this version of Python.
Once this is completed, our new version Python3.7.2 is installed and ready to use.
# python3.7 -v Python 3.7.2 [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux Type "help", "copyright", "credits" or "license" for more information.
If you see an error “ModuleNotFoundError: No module named ‘_ctypes’” , make sure, you have “libffi-devel” installed
# yum install libffi-devel
and start again with ./configure command
After installation, if python3.7 -v returns “Command Not Found” error, make sure the $PATH variable have /usr/local/bin.
# echo $PATH
If its not there, add it using
# export PATH=$PATH:/usr/local/bin
That’s it. This is how to install Python 3 on CentOS 7 from source. Its pretty easy, right? If you enjoy it, let us know in the comments below!