ModuleNotFoundError: No module named ‘numpy‘ 解决方案

问题描述

今天做 NLA 的作业,需要使用 gaussian elimination,不是特别想用 C++ 来完成,主要是太麻烦。于是就准备使用自己贫瘠的 Python 来完成。

啪啦啪啦打了一堆代码,然后在 VSCode 上运行。我去,什么反馈都没有。蒙了,缓了一口气,让我懵逼的大脑休息一下。切换到 Terminal 来调试。

前面先是 print 的几个语法错误,轻松解决。

File "gaussian_elim.py", line 23
    print A
          ^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(A)?

语法错误解决后,开始大餐。

% python3 gaussian_elim.py
Traceback (most recent call last):
  File "gaussian_elim.py", line 1, in <module>
    import numpy as np
ModuleNotFoundError: No module named 'numpy'

什么意思?没有安装 numpy。好吧。立马 pip3 install numpy,看到系统反馈如下。

% pip3 install numpy
Requirement already satisfied: numpy in /usr/local/lib/python3.8/site-packages (1.19.1)

继续 pyhon3 gaussian_elim.py 还是同样的问题,numpy 包没有找到。这下更懵逼了。

% pip3 list
Package    Version
---------- -------
numpy      1.19.2
pip        20.1.1
protobuf   3.13.0
PyQt5      5.15.0
PyQt5-sip  4.19.24
setuptools 49.2.0
six        1.15.0
TBB        0.1
wheel      0.34.2

这里不是有 numpy 啊。WTF。

认真考虑了几秒,实际是好几分钟,会不会是我机器安装了两个版本 numpy 导致啊。

% sudo python3 -m pip install numpy
Password:
The directory '/Users/yeecall/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/Users/yeecall/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Collecting numpy
  Downloading https://files.pythonhosted.org/packages/c1/a9/f04a5b7db30cc30b41fe516b8914c5049264490a34a49d977937606fbb23/numpy-1.19.2-cp37-cp37m-macosx_10_9_x86_64.whl (15.3MB)
    100% |████████████████████████████████| 15.3MB 1.5MB/s 
Installing collected packages: numpy
Successfully installed numpy-1.19.2

验证一下 numpy 是否安装好。

% python3 
Python 3.7.3 (default, Aug  4 2020, 19:30:55) 
[Clang 11.0.3 (clang-1103.0.32.62)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
exit()>>> print (numpy.__version__)
1.19.2

我的天,终于正常了。

问题可能原因

可能是 MBP 上存在两个版本的 Python,即 Python2 和 Python3 导致。

解决方法

指定 python3 安装 numpy 包。使用 python3 -m pip install numpy,注意有权限问题的话,使用 sudo python3 -m pip install numpy。

猜你喜欢

转载自blog.csdn.net/justidle/article/details/108792181