如何授予 python 对 ubuntu 中系统范围模块的访问权限?

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

我在 Ubuntu 16.04(64 位版本)中安装了 python 2.7.12。我也通过 pip 安装了 numpy、scipy、sympy 等模块。我的问题是,当我通过终端打开 python 命令行并尝试导入这些模块时,出现以下错误:

$ 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
>>>

经过一些研究,我发现 thread 如果我使用 /usr/bin/python 打开 python 命令行并尝试导入这些模块,我不会收到任何错误。

$ /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
>>> 

但我想知道是否有任何方法可以让我从终端输入 python 并在 python 命令行中导入这些模块?例如,如果我写这样一个程序,

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

import numpy
import scipy
import sympy

将其保存在我桌面上名为 test.py 的文件中,然后使用命令 /usr/bin/python test.py 打开它,我得到了所需的输出。

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

但是如果我用命令 python test.py 尝试相同的操作,我会再次收到错误消息

$ 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

据我了解,python 无法访问系统范围的模块,因为它是在本地安装的。如果是这样,有没有办法使 python 全局或 python 本地模块?在过去的几个小时里,我一直在尝试寻找解决方案,但我还没有找到任何东西,而且我是 Linux 的新手。感谢您的帮助。

我认为根本原因是您在 $PATH 下有几个 python 二进制文件,而您的系统默认情况下不使用 /usr/bin/python

  1. 运行命令which python查看默认使用哪个python
  2. 将默认 python 文件重命名为 'python-2-7-12'

然后再尝试运行python test.py看是否解决。