Sideload Python 3 on a CentOS 7 with Python 2 installed

Audun Nes
2 min readDec 29, 2020

--

There might be good reasons why you need to keep Python 2 as the default Python version on your CentOS 7 server for legacy applications, but keep in mind that Python 2.7 reached End of Life on the 31st of December 2019.

Compile Python 3 from source

This is of course only needs to be done once, and it has to be done by the root user.

yum install gcc openssl-devel bzip2-devel libffi-devel
mkdir -p /tools/python3.8
cd /tools
curl -LO https://www.python.org/ftp/python/3.8.7/Python-3.8.7.tgz
# Currently the lastest stable release
tar xvf Python-3.8.7.tgz
rm -f Python-3.8.7.tgz

cd Python-3.8.7
./configure --prefix=/tools/python3.8 --enable-optimizations
# Please note that we need to specify an alternate
# output directory by using --prefix
make && make install

If you get the following error:

Could not import runpy module
Traceback (most recent call last):
File “/home/jeremyr/Python-3.7.3/Lib/runpy.py”, line 15, in <module>
import importlib.util
File “/home/jeremyr/Python-3.7.3/Lib/importlib/util.py”, line 14, in <module>
from contextlib import contextmanager
File “/home/jeremyr/Python-3.7.3/Lib/contextlib.py”, line 4, in <module>
import _collections_abc
SystemError: <built-in function compile> returned NULL without setting an error
generate-posix-vars failed

Then compile again without optimizations:

cd Python-3.8.7
./configure — prefix=/tools/python3.8
make clean
make install

Install common packages globally

Many Python packages depends on the wheel and pbr packages. On CentOS and its upstream source the selinux package is also needed. I am also a big fan of using virtualenvwrapper to manage Python’s virtual environments, so I will install these four packages globally as root user:

chmod -R 755 /tools/python3.8
/tools/python3.8/bin/python3 -m pip install pbr
/tools/python3.8/bin/python3 -m pip install wheel
/tools/python3.8/bin/python3 -m pip install virtualenvwrapper
/tools/python3.8/bin/python3 -m pip install selinux

Configure virtualenvwrapper for my user

After I have logged in to the CentOS 7 Linux as my own non-privileged user, I need to configure virtualenvwrapper:

echo "export VIRTUALENVWRAPPER_PYTHON=/tools/python3.8/bin/python3" >> ~/.bashrcecho "export VIRTUALENVWRAPPER_VIRTUALENV=/tools/python3.8/bin/virtualenv" >> ~/.bashrcecho "source /tools/python3.8/bin/virtualenvwrapper.sh" >> ~/.bashrcsource ~/.bashrc

Create my first virtual environment

In this simple example I create a Python virtual environment called myenv with the flake8 package.

mkvirtualenv myenv
pip install flake8

--

--

Audun Nes

Lead Cloud Engineer/Site Reliability Engineer from Copenhagen, Denmark. GitHub: https://github.com/avnes