pip安装了mysqlclient,测试mysqlclient安装情况python -c "import MySQLdb;print(MySQLdb.__file__),报下面的错:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/Users/XX/.pyenv/versions/py37/lib/python3.7/site-packages/mysqlclient-1.3.7-py3.7-macosx-15.3-arm64.egg/MySQLdb/__init__.py", line 19, in <module>
    import _mysql
ImportError: dlopen(/Users/XX/.pyenv/versions/py37/lib/python3.7/site-packages/mysqlclient-1.3.7-py3.7-macosx-15.3-arm64.egg/_mysql.cpython-37m-darwin.so, 0x0002): Library not loaded: libmysqlclient.18.dylib
  Referenced from: <9F121531-5C6A-36F2-BC36-852DDDE9C46B> /Users/XX/.pyenv/versions/3.7.17/envs/py37/lib/python3.7/site-packages/mysqlclient-1.3.7-py3.7-macosx-15.3-arm64.egg/_mysql.cpython-37m-darwin.so
  Reason: tried: 'libmysqlclient.18.dylib' (no such file), '/System/Volumes/Preboot/Cryptexes/OSlibmysqlclient.18.dylib' (no such file), 'libmysqlclient.18.dylib' (no such file), '/Users/XX/Downloads/libmysqlclient.18.dylib' (no such file), '/System/Volumes/Preboot/Cryptexes/OS/Users/XX/Downloads/libmysqlclient.18.dylib' (no such file), '/Users/XX/Downloads/libmysqlclient.18.dylib' (no such file)

应该是在查找动态库的时候查找失败了。
方法1,通过 export DYLD_LIBRARY_PATH=/usr/local/mysql/lib/:$DYLD_LIBRARY_PATH 来指定库文件位置。(但没用)

方法2:
A、先查看so的文件依赖

执行命令 otool -L /Users/XX/.pyenv/versions/3.7.17/envs/py37/lib/python3.7/site-packages/mysqlclient-1.3.7-py3.7-macosx-15.3-arm64.egg/_mysql.cpython-37m-darwin.so 输出:

/Users/XX/.pyenv/versions/3.7.17/envs/py37/lib/python3.7/site-packages/mysqlclient-1.3.7-py3.7-macosx-15.3-arm64.egg/_mysql.cpython-37m-darwin.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 1351.0.0)

表示对libmysqlclient.18.dylib的依赖没用设置路径,所以会通过查找的方式来定位动态库路径。

下面是把so文件里面的依赖直接设置成固定的路径,避免找不到,同时也提高了查找效率。

执行命令 sudo install_name_tool -change libmysqlclient.18.dylib /usr/local/mysql/lib/libmysqlclient.18.dylib /Users/XX/.pyenv/versions/3.7.17/envs/py37/lib/python3.7/site-packages/mysqlclient-1.3.7-py3.7-macosx-15.3-arm64.egg/_mysql.cpython-37m-darwin.so

成功之后在看so的依赖

执行命令 otool -L /Users/XX/.pyenv/versions/3.7.17/envs/py37/lib/python3.7/site-packages/mysqlclient-1.3.7-py3.7-macosx-15.3-arm64.egg/_mysql.cpython-37m-darwin.so 输出:

/Users/XX/.pyenv/versions/3.7.17/envs/py37/lib/python3.7/site-packages/mysqlclient-1.3.7-py3.7-macosx-15.3-arm64.egg/_mysql.cpython-37m-darwin.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 1351.0.0)

可以看到已经修改了。

再次执行测试也能导入MySQLdb成功了。

python -c "import MySQLdb;print(MySQLdb.__file__)


RobinTang
3.9k 声望37 粉丝