解决macOS下,python2调用MySQL报错_mysql.so Reason: image not found的问题

内容纲要

背景

这几天遇到一个问题,在mac环境下写python脚本,发现自建的mysql无法调用。报错如下:

ImportError: dlopen(/Users/geenquan/miniconda2/envs/py27/lib/python2.7/site-packages/MySQLdb/_mysql.so, 2): Library not loaded: @rpath/libmysqlclient.21.dylib
  Referenced from: /Users/geenquan/miniconda2/envs/py27/lib/python2.7/site-packages/MySQLdb/_mysql.so
  Reason: image not found


这个问题在百度上找了很久,但是没有具体的解决方案。后来查找了谷歌,找到了解决办法。

原因

造成这个现象的原因是,mysql的包(libmysqlclient.21.dylib)找不到,所以解决办法比较明确,让程序能找到的就可以。

解决办法

解决办法也比较直接,让程序直接能找到即可。第一种方法,也是谷歌上推荐最多的,对这个包进行一个链接。通过ln命令把libmysqlclient.21.dylib包连接到/usr/lib下面,这样全局都能用了。

首先找到libmysqlclient.21.dylib的位置,在macos中存在于/usr/local/mysql/lib下,现在需要把它链接到/usr/lib下,具体命令如下:

sudo ln -s /usr/local/mysql/lib/libmysqlclient.21.dylib /usr/lib/libmysqlclient.21.dylib

但是遇到一个新的问题,在macos中报权限不允许的错

ln: /usr/lib/libmysqlclient.21.dylib: Operation not permitted

经过查询得知,macos不允许对/usr/lib下的文件进行链接,那么就把这条路堵死了。

后来想到了既然usr/lib是一个全局能找到的地址,那我把这个文件放在环境变量里是否就可以了。于是,在~/.barhrc_profile下增加一行环境变量

export DYLD_LIBRARY_PATH=/usr/local/mysql/lib:$DYLD_LIBRARY_PATH

执行命令

source .barhrc_profile

再次调用,发现问题已经解决。希望这篇博客能够帮助到大家,解决mac环境下的mysql包的问题。

38 thoughts on “解决macOS下,python2调用MySQL报错_mysql.so Reason: image not found的问题”

  1. Hiya, I am really glad I have found this info. Nowadays bloggers publish only about gossip and internet stuff and this is actually annoying. A good site with interesting content, this is what I need. Thank you for making this web site, and I will be visiting again. Do you do newsletters by email? Wynnie Dillon Johnston

  2. Excellent read, I just passed this onto a friend who was doing some research on that. And he just bought me lunch because I found it for him smile Thus let me rephrase that: Thank you for lunch! Moira Giulio Elish

  3. Quisque vulputate lorem a nisl faucibus, eu consectetur leo maximus. Nulla facilisis nisi nunc, ac tempor ipsum dapibus non. Curabitur non iaculis dui, eu tempus ipsum. Fusce ut porta urna. In sit amet pharetra ligula. Ut posuere quis elit laoreet efficitur. Daria Dick Biddick

  4. Thank you for taking the time to discuss this particular, I feel strongly about this as well as love learning more on this subject. If at all possible, Fern Lester Enoch

  5. Its not my first time to pay a quick visit this website, i am browsing this site dailly and obtain pleasant facts from here everyday.| Stacia Loydie Giliana

  6. After reading the topic several times, I feel that I need to republish it on my blog. After the admin’s permission, I will share the topic on my personal page. I hope for more useful topics of this type.

发表评论

邮箱地址不会被公开。 必填项已用*标注