在anaconda3 python3.6.5环境中导入cv2报错:
$ python
Python 3.6.5 |Anaconda, Inc.| (default, Apr 29 2018, 16:14:56)
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: /opt/ros/kinetic/lib/python2.7/dist-packages/cv2.so: undefined symbol: PyCObject_Type
从报错可以看出,在python3.6.5虚拟环境中,程序试图从 /opt/ros/kinetic/lib/python2.7/dist-packages/ 路径下导入cv2.so库文件。然而,该路径下的库文件是属于python2.7(普通环境)的,python3.6.5的cv2.so文件安装在虚拟环境对应的路径之下。
因此,虚拟环境中,程序得从/lib/python3.6.5/site-packages 路径下导入cv2.so文件。
解决方法:
如何修改python程序读取库文件的路径呢?
首先介绍2种方法,用于查看python读取库文件路径(以python3.5的环境为例)
- 读取环境变量$PYTHONPATH
$ echo $PYTHONPATH
/home/lufeng/ros_ekf/devel/lib/python2.7/dist-packages:/home/lufeng/Delphi_ws/devel/lib/python2.7/dist-packages:/home/lufeng/Basler_ws/devel/lib/python2.7/dist-packages:/home/lufeng/tutorial_ws/devel/lib/python2.7/dist-packages:/opt/ros/kinetic/lib/python2.7/dist-packages
- 在python控制台中查看
~$ python
Python 3.6.5 |Anaconda, Inc.| (default, Apr 29 2018, 16:14:56)
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/home/lufeng/ros_ekf/devel/lib/python2.7/dist-packages', '/home/lufeng/Delphi_ws/devel/lib/python2.7/dist-packages', '/home/lufeng/Basler_ws/devel/lib/python2.7/dist-packages', '/home/lufeng/tutorial_ws/devel/lib/python2.7/dist-packages', '/opt/ros/kinetic/lib/python2.7/dist-packages', '/home/lufeng/anaconda3/lib/python36.zip', '/home/lufeng/anaconda3/lib/python3.6', '/home/lufeng/anaconda3/lib/python3.6/lib-dynload', '/home/lufeng/anaconda3/lib/python3.6/site-packages']
可以发现,两种方式出现了路径 /opt/ros/kinetic/lib/python2.7/dist-packages ,且其优先级比路径 ~/Anaconda3/lib/python3.6.5/site-packages 高。
我们希望程序优先读取python3.6.5的库路径,对应有两种方式!
1.修改环境变量$PYTHONPATH
export PYTHONPATH=/home/xxxxx/Anaconda3/lib/python3.6.5/site-packages
当使用命令激活ROS时,即运行 source /opt/ros/kinetic/setup.bash
,ROS会添加 /opt/ros/kinetic/lib/python2.7/dist-packages
到python路径。因此,需要在 .bashrc 文件中注释掉该命令行,并再次source读取环境变量。
vim ~/.bashrc
- 在python控制台中移除错误路径
~$ python
Python 3.6.5 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: /opt/ros/kinetic/lib/python2.7/dist-packages/cv2.so: undefined symbol: PyCObject_Type
>>> import sys
>>> sys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages')
>>> import cv2