-
Mac OS X下python环境下安装MySQL-python, 使用是报错
>>> import MySQLdb Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/site-packages/MySQLdb/__init__.py", line 19, in <module> import _mysql ImportError: dlopen(/usr/local/lib/python2.7/site-packages/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib Referenced from: /usr/local/lib/python2.7/site-packages/_mysql.so Reason: image not found
stackoverflow上可以找到解决方式 Python mysqldb: Library not loaded: libmysqlclient.18.dylib
-
基本思路就是
-
_mysql.so如何找libmysqlclient.18.dylib
% otool -L /Library/Python/2.7/site-packages/_mysql.so /Library/Python/2.7/site-packages/_mysql.so: libmysqlclient.18.dylib (compatibility version 18.0.0, current version 18.0.0) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 169.3.0)
-
libmysqlclient.18.dylib没有路径信息, 修复
% sudo install_name_tool -change libmysqlclient.18.dylib /usr/local/mysql/lib/libmysqlclient.18.dylib /Library/Python/2.7/site-packages/_mysql.so
-
修复后, 查看:
% otool -L /Library/Python/2.7/site-packages/_mysql.so /Library/Python/2.7/site-packages/_mysql.so: /usr/local/mysql/lib/libmysqlclient.18.dylib (compatibility version 18.0.0, current version 18.0.0) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 169.3.0)
-
使用brew安装的mysql, 而且是5.7版本, dylib的位置是:
/usr/local/lib/libmysqlclient.20.dylib
修复的方式是(dylib换成自己环境的位置):
sudo install_name_tool -change libmysqlclient.18.dylib /usr/local/lib/python2.7/site-packages/_mysql.so /usr/local/lib/libmysqlclient.20.dylib
如果用虚拟环境, 每个环境都需要类似的执行一次, 有点麻烦, 暂时我想到的解决方式是使用脚本(fix-mysql-python.sh), shell代码如下:
PACKAGES_PATH=`python -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())"`
echo $PACKAGES_PATH
install_name_tool -change libmysqlclient.18.dylib /usr/local/lib/libmysqlclient.20.dylib $PACKAGES_PATH/_mysql.so
echo "fix MySQL-python finish"