Saturday, July 9, 2016

Running Multiple Versions of Python on a Single Linux System

While some Python applications are written in Python 3, some others are still being maintained and developed in Python 2. That is to say, there is a need to run multiple versions of Python on a single system. The following steps show that you can install multiple versions of Python on a single Linux system, and activate and deactivate the version you wish to use conveniently by leveraging on virtual python environments. Note that the following steps are tested on a Debian-based Linux system, such as Debian Linux and Ubuntu Linux

  1. Install the Python 2 and Python 3 if you have not done so.
    sudo apt-get install python python3

  2. Install python-virtualenv packages. This step is the key.
    sudo apt-get install python-virtualenv

  3. Show that you have both python 2 and 3 binaries. In the Linux system I am using for this post, the python binary by default points to Python 2's binary. Yours may differ.
    $ python --version
    Python 2.7.6
    $ python3 --version
    Python 3.4.3

  4. To develop or run some applications in python 3, we need to activate Python 3. Then, first create a directory as the working directory for the Python 3 application. For instance, we name the directory as proj_python_3.
    $ mkdir proj_python_3

  5. Now switch to the directory.
    cd proj_python_3
    $ which python3

  6. Then activate Python 3, we first need to set up an environment in the working directory for Python 3.
    $ virtualenv -p /usr/bin/python3 .env
    Running virtualenv with interpreter /usr/bin/python3
    Using base prefix '/usr'
    New python executable in .env/bin/python3
    Also creating executable in .env/bin/python
    Installing setuptools, pip...done.

  7. Now we can activate Python 3 any time we wish after we switch to the working directory.
    $ pwd
    $ . .env/bin/activate

    Note that the prompt shows that you are under a virtual environment for Python 3. You can show that the activated Python version is Python 3.
    (.env)$ python --version
    Python 3.4.3

  8. To deactivate the virtual environment, run the following,
    (.env)$ deactivate
    $ python --version
    Python 2.7.6

At present, the working directory for the virtual python environment must be on a file system that supports symbolic links; otherwise step 6 will fail.

1 comment:

  1. Great article, was easier for me to follow this one than other ones.