Search code examples
pythonpython-2.7python-3.xcompatibility

Python 2.7 and 3.4: Libraries inaccessible across versions


I am new to Python. I am running Ubuntu 14.04, and I have both Python 2.7 and 3.4 on it.

I want to use the newer 3.x version, with the NumPy, SciPy, and NLTK libraries. I set the Python REPL path to Python 3.x in the ~/.bash_aliases file like so:

alias python=python3

After this I installed several libs, including python-numpy, python-scipy, and python-matplotlib.

$ sudo apt-get install python-numpy python-scipy python-matplotlib ipython ipython-notebook python-pandas python-sympy python-nose

Unfortunately, I am facing issues since I am guessing that the libraries got installed for the older 2.7 version of Python; I am unable to access the libraries using the 3.4 REPL.

import numpy

ImportError: No module named 'numpy'

However, I am able to access the libraries using the older version:

$ /usr/bin/python2.7

How do I get this this work?


Solution

  • When you install Python packages using apt-get, you're relying on the distribution package manager. The Ubuntu convention is to prefix Python 2 packages with python-, and Python 3 packages with python3-.

    This distinction is necessary because Python 3 introduced some incompatible changes from Python 2. It's thus not possible to simply recompile (most) packages for Python 3, meaning both need to be made available.

    Alternatively, you can use the Python package manager, pip (or pip3). The catch with this is that some packages (like scipy) require certain compiler toolchains which you might not have installed.

    It's generally a good idea to stick to either apt-get or pip for a particular machine. You probably won't have issues if you mix them, but it's better to be consistent.