Table of contents
Open Table of contents
Intro
CentOS 7 has Python 2.7 installed out of the box and is used by the system itself to enable quite a few handy commands, such as yum.
As a Python coder I too have been struggling to decide between Python 2 and Python 3 for new projects. I made the transition to Python 3 during last year, for the benefits it gives me out of the box, e.g. default Unicode support. Read more here and here. It’s worth to note, that not all projects are supporting Python 3, yet.
So, how can I run my apps on server, which does not have Python 3 installed without breaking the system (by replacing system Python 2.7)?
Let’s get started.
Install the necessary utilities
This guide assumes, that you are working on updated CentOS 7 server with a user with sudo priviledges.
$ sudo yum install yum-utils make wget
Install missing dependencies and set up a necessary build environment for Python 3
$ sudo yum-builddep python
Download and install Python 3.5.1 from source
I chose to install Python 3 from source, since yum (from EPEL repo) does not provide version 3.5 yet.
I work in dir /home/user/source
.
To download the source tarball
$ wget https://www.python.org/ftp/python/3.5.1/Python-3.5.1.tgz
Decompress the package
$ tar xzf Python-3.5.1.tgz
Compile the sources
cd Python-3.5.1
./configure
make
… And finally install Python 3.5.1. This will install Pip (The Python package manager, which we all love) too. Note! I do the install with altinstall
to make sure I do not mess with the system Python.
$ sudo make altinstall
Ready to test:
# This should return the system Python version
$ python –V
Python 2.7.5
... as it does.
# This should return the Python 3 version
$ python3.5 –V
Python 3.5.1
That’s it. Now I have Python 3 ready run my apps!
Epilogue
Few additional notes.
Alias
Few aliases, which helps in the long run. Add these to your .bashrc
alias python3='/usr/local/bin/python3.5'
alias pip3='/usr/local/bin/pip3.5'
# (without this sudo does not see aliases)
alias sudo='sudo '
Virtualenv tutorial
How to create a new virtualenv with Python 3:
- Install virtualenv globally with
$ sudo pip3 install virtualenv
- In project home (e.g.
/home/user/projects/
) run$ virtualenv -p python3.5 demoproject
- Activate the virtualenv to use with
$. demoproject/bin/activate