0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【エラー】ImportError: dlopen(..._mysql.cpython-39-darwin.so, 0x0002): Library not loaded: /opt/homebrew/opt/mysql/lib/libmysqlclient.24.dylib について

Last updated at Posted at 2025-04-23

はじめに

ログが消えてしまい、再度環境構築しようとしたところ大変なことになったので覚えてるところまでかきます。ぬけおちていたらすみません。
以下は自分用の備忘録ですが、同じように MySQL 8.0.42 mysqlclient==2.0.3 の組み合わせを使っていて M1 Mac(Apple Silicon)で苦戦している方の参考になれば幸いです。

MySQLとmysqlclientのバージョン

MySQL 8.0.42
mysqlclient 2.0.3

brewを使用してインストールしています。

発生したエラー

ImportError: dlopen(..._mysql.cpython-39-darwin.so, 0x0002): 
Library not loaded: /opt/homebrew/opt/mysql/lib/libmysqlclient.24.dylib

意味としては
libmysqlclient.24.dylibが存在しないよー
ってことです。

mysqlclient==2.0.3MySQL 8.0.24頃のlibmysqlclient.24.dylib を探しているけれども
今使っている環境にはlibmysqlclient.21.dylibしかない。

この問題の解決方法として以下の2つの方法を考えました。

解決方法その1 mysqlclientをアップグレードする

シンプルな方法としてmysqlclient をアップグレードする。

pip install --upgrade mysqlclient

でも、今回は「環境を汚したくない」ので以下の方法を選択。

解決方法その2 mysqlclientをインストールし直す

# MySQLビルド環境のパスを通す
export PATH="/opt/homebrew/opt/mysql@8.0/bin:$PATH"
export LDFLAGS="-L/opt/homebrew/opt/mysql@8.0/lib"
export CPPFLAGS="-I/opt/homebrew/opt/mysql@8.0/include"
# 仮想環境を削除
rm -rf .venv
# 仮想環境を再構築
pipenv install --dev
# 仮想環境に入る
pipenv shell
# 念のためもう一度 export(仮想環境に入ると上書きされる可能性があるため)
export PATH="/opt/homebrew/opt/mysql@8.0/bin:$PATH"
export LDFLAGS="-L/opt/homebrew/opt/mysql@8.0/lib"
export CPPFLAGS="-I/opt/homebrew/opt/mysql@8.0/include"
# mysqlclientのアンインストール
pip uninstall mysqlclient -y
# setuptoolsのバージョンを下げる これをしないとmysqlclientがインストールできない
pip install "setuptools==60.0.0"
# 2.0.3をインストールする
pip install --no-cache-dir --force-reinstall mysqlclient==2.0.3
# setuptoolsを元のバージョンに戻す
pip install "setuptools==78.1.0"

無理矢理ですがこれでrunserverできるようになりました!

おまけ

毎回 export が面倒な場合は.zshrcに以下を追記しておくと便利です!

echo 'export PATH="/opt/homebrew/opt/mysql@8.0/bin:$PATH"' >> ~/.zshrc
echo 'export LDFLAGS="-L/opt/homebrew/opt/mysql@8.0/lib"' >> ~/.zshrc
echo 'export CPPFLAGS="-I/opt/homebrew/opt/mysql@8.0/include"' >> ~/.zshrc
source ~/.zshrc
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?