rsnaveen rsnaveen - 5 months ago 16
Linux Question

How to give python access to system wide modules in ubuntu?

I have python 2.7.12 installed in Ubuntu 16.04 (64-bit version). I have modules such as numpy, scipy, sympy etc. installed via pip as well. My problem is, when I open python command line via Terminal and try to import these modules, I get the following error:

$ python
Python 2.7.12 (default, Jul 10 2016, 20:42:07)
[GCC 5.3.1 20160413] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named numpy
>>>


Upon doing some research, I found from this thread that if I open python command line using
/usr/bin/python
and try importing these modules, I don't get any errors.

$ /usr/bin/python
Python 2.7.11+ (default, Apr 17 2016, 14:00:29)
[GCC 5.3.1 20160413] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>> import scipy
>>> import sympy
>>> import matplotlib
>>> import pandas
>>>


But I would like to know if there is any way I can just type in
python
from Terminal and import these modules in the python command line? For example, if I write a program like this,

x = 2
print x
y = 5
print y
print x+y

import numpy
import scipy
import sympy


save it in a file named test.py in my desktop and open it using the command
/usr/bin/python test.py
, I am getting the desired output.

$ /usr/bin/python test.py
2
5
7


But if I try the same with the command
python test.py
, I get the error again

$ python test.py
2
5
7
Traceback (most recent call last):
File "test.py", line 8, in <module>
import numpy
ImportError: No module named numpy


From what I understand, python doesn't have access to system wide modules since it is installed locally. If so, is there a way to make python global or the modules local to python? I have been trying for the past couple of hours to find a solution but I haven't found anything yet and I am new to Linux. Thanks for your help.

Answer

I think the root cause is you have several python binary under $PATH, and your system doesn't use /usr/bin/python by default.

  1. run command which python to see which python is used by default
  2. rename the default python file to something like 'python-2-7-12'

then try to run python test.py again to see if it is resolved.