Do "python3" and "python" use different path variables?

The command python opens a Python 2.7.6 environment. If I want to interpret a Python 3 script, I need to rewrite the command to python3.

I've just installed the numpy package. In order to test the successful installation, I run the command import numpy. It works well when using the python command. However, python3 does not find the package.

How is this possible? Do these two commands use different path variables? How can I change the behavior?


Solution 1:

You're absolutely right, they use different PYTHONPATHs.

You can think of Python 2.x and Python 3.x as completely different programming environments. And yes, they store their packages in different locations.

To get numpy working, you can type:

sudo apt-get install python3-numpy

If you want to find out where exactly a package is kept, you can look at the module objects __path__ attribute:

>>> import numpy
>>> numpy.__path__
['/usr/local/lib/python3.5/site-packages/numpy']

You can also install python3-pip and then run pip3 install whatever to install packages for Python 3 with Pip, for packages that aren't available in Ubuntu as python3-whatever.

In case you're confused about the difference between distutils, setuptools, easy_install, pip and the rest, use pip. That's the cool one. :)

Solution 2:

No, they use the same PATH. However, this problem isn't with the PATH.

Python 2 and Python 3 are sufficiently different that packages have to be written separately for both of them. You cannot use a package written for one with the other.

In Ubuntu, these modules are stored in different locations and are packaged separately - python-numpy for Python 2, python3-numpy for Python 3. If you want numpy with Python 3, install python3-numpy.

$ python3 -c 'import sys; print (sys.path)'
['', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/usr/lib/python3.4/lib-dynload', '/home/muru/.local/lib/python3.4/site-packages', '/usr/local/lib/python3.4/dist-packages', '/usr/lib/python3/dist-packages']
$ python2 -c 'import sys; print (sys.path)'
['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client']

Solution 3:

Indeed, both are importing modules from different locations:

  • Python2.7: /usr/lib/python2.7/dist-packages/numpy/
  • Python3.x: /usr/lib/python3/dist-packages/numpy/

To be able to import numpy with both interpreters, be sure to install their corresponding packages:

  • Python2.7: sudo apt-get install python-numpy
  • Python3.x: sudo apt-get install python3-numpy