Step 1: Install Required Dependencies

First, you’ll need to install the development tools and libraries required to build Python from the source. Open a terminal and run:

1
2
sudo yum groupinstall "Development Tools"
sudo yum install openssl-devel bzip2-devel libffi-devel

Step 2: Download Python(Or other version you intend to upgrade)

You can download Python 3.8.13 from the official Python website. Use wget to download it directly to your CentOS machine:

1
wget https://www.python.org/ftp/python/3.8.13/Python-3.8.13.tgz

Step 3: Extract and Install Python

After downloading, extract the tarball and install Python. Run these commands:

1
2
3
4
tar xzf Python-3.8.13.tgz
cd Python-3.8.13
./configure --enable-optimizations
make altinstall

Using make altinstall instead of make install prevents replacing the default system python binary.

Find the Python you’ve installed

1
ls /usr/local/bin/python*

It might look like:

1
/usr/local/bin/python3  /usr/local/bin/python3.8

Now set the latest version to default:

1
2
3
sudo alternatives --install /usr/bin/python3 python3 /usr/local/bin/python3.8 1

sudo alternatives --config python3

It might shows:

1
2
3
4
5
6
7
There is 1 program that provides 'python3'.

Selection Command
-----------------------------------------------
*+ 1 /usr/local/bin/python3.8

Enter to keep the current selection[+], or type selection number:

In my situation, input 1 and Enter.

Set environment

1
export PATH=/usr/local/bin:$PATH

Set it in .bashrc:

1
vim ~/.bashrc

Add

1
export PATH=/usr/local/bin:$PATH

to .bashrc file, enter :wq save and quit.

Then activate:

1
source ~/.bashrc

Verify final result

1
python -V