python 无法识别导入 pyserial/serial,但已安装依赖项 [Mac]

import pyserial / serial not recognized by python, but dependencies already installed [Mac]

已安装 pyserial 的依赖项,在 python

中无法识别调用 pyserial
Maxs-MacBook:~ grax$ sudo pip install pyserial
The directory '/Users/grax/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/grax/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.
Requirement already satisfied: pyserial in /Library/Python/2.7/site-packages
Maxs-MacBook:~ grax$ python
Python 2.7.15 (default, May  2 2018, 00:53:27)
[GCC 4.2.1 Compatible Apple LLVM 9.1.0 (clang-902.0.29.1] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pyserial
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Import Error: No module named pyserial

我该怎么办?

即使您调用 pip pyserial,python 模块也会被调用 serial。令人困惑,是的。

import serial

另一个问题可能是您正在使用的 python 实例与 pip 安装的实例不同。

查看 pip 安装模块的位置:

$ pip show pyserial
Name: pyserial
Version: 3.4
Summary: Python Serial Port Extension
Home-page: https://github.com/pyserial/pyserial
Author: Chris Liechti
Author-email: cliechti@gmx.net
License: BSD
Location: /Library/Python/2.7/site-packages

因为您的位置是 /Library/Python2.7... pip 似乎正在安装在系统目录中。

但是,您使用的 python 版本 (Python 2.7.15) 不是 MacOSX 附带的版本,因此它可能正在某处寻找 python 模块否则。

$ python
>>> import sys
>>> print sys.path

pip 的版本很可能 安装在那里。 (pip 不是 MacOS 原生的,所以它可能使用 /usr/local/bin/python/usr/local/lib/python2.7/site-packages

您可以使用 --target 选项强制 pip 安装到其他地方:

$ sudo pip install --target /usr/local/lib/python2.7/site-packages pyserial

这会将 serial 模块放在您 python 查找的位置。