CentOS 6 comes with Python 2.6 installed, and CentOS 7 comes with Python 2.7. But right now, Python 3.5 is all the rage, so I thought I’d install it alongside Python 2.x on the same machine.
Here’s how I did it.
I’m using a CentOS 6 32 bit system here, but I’ve tried the same on a CentOS 7 64 bit rig. You need to be root or have superuser privileges to do this successfully.
First, we’ll download the package from http://python.org. Head over to the downloads section, then scroll to the bottom and find direct source links to both Python 2 and 3 at the bottom of the page.
Now we’ll extract the package:
tar -Jxvf Python*
This will give us a new directory, in my case it’s called Python-3.5.2 (depending on the current version number). Let’s cd into it and use configure and make to start our build:
cd Python* ./configure make
And finally, let’s install Python:
If you encounter any errors along the way, it’s likely that you’re missing some packages on the current system. Not to worry, the following should install what you need:
yum install wget make gcc
How do I use Python 3?
Python 3 is now installed in /usr/local/bin, in my case as/usr/local/bin/python3.5. The exact path depends on the version number. In addition, a symbolic link has been created as /usr/local/bin/python3.
You can use your new Python version in shell scripts by starting your script with a she-bang referencing this version:
To youse Python 3 from the command line, make sure to execute the full path to it, or amend your shell accordingly.
Can I still use Python 2?
Yes you can, in fact CentOS depends on it. The default Python2 installation is installed in /usr/bin/python2.x, with a symbolic link /usr/bin/python.
If you type “python” at the command prompt, you’ll see it’s still version 2:
python --version Python 2.6.6
python Python 2.6.6 (r266:84292, Aug 18 2016, 14:53:48) [GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>>
To run a shell script with Python 2, use the following she-bang at the beginning:
Can I upgrade and replace Python 2 with Python 3?
That is not a good idea, and I’m not sure if it’s possible without compromising the operating system. From what I understand, Python 2 and 3 are fundamentally different. For example, diving 2 by 3 will deliver a rounded integer in Python 2, but a float in Python 3.
Since CentOS relies on Python 2 to work, and expects Python 2 behaviour, I bet there would be issues.
Isn’t there an easier way to get Python 3 on CentOS?
Yes there is – you could install a precompiled package from the EPEL repository, it’ll do more or less the same job:
yum install python34
(But part of the “fun” of working with Linux is to install from source every once in a while).