99.9% 的人不需要看這篇文章。我是說真的搀矫。
寫在前面
好久沒有寫這種類型的文章了夏伊,記錄遇到的具體問題摇展。
隨著搜索水平的提高,特別是英文搜索水平的提高溺忧,這種類型的文章感覺越來越沒有價值咏连,因為一搜索就找到了答案。難怪大家說砸狞,現(xiàn)在的程序員 = 搜索引擎 + Ctrl+C + Ctrl+V 捻勉。
今天寫這個文章是因為花了吃奶的力氣仍然搜索不到答案,最后還是靠經驗和基礎知識解決刀森。問題是這樣,在 macOS Sierra 上使用 pip 安裝 mysqlclient 時遇到錯誤报账,無法鏈接到 libssl 庫研底,系統(tǒng)上明明安裝了 openssl 可是就是鏈接不到埠偿。
看到這里,99% 的讀者可以關掉這個頁面走人了榜晦。
問題現(xiàn)象
系統(tǒng)安裝了 mysql 冠蒋,使用 pip install mysqlclient
時出錯,錯誤信息如下:
building '_mysql' extension
creating build/temp.macosx-10.6-intel-3.5
/usr/bin/clang -fno-strict-aliasing -Wsign-compare -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -arch i386 -arch x86_64 -g -Dversion_info=(1,3,9,'final',1) -D__version__=1.3.9 -I/usr/local/Cellar/mysql/5.7.16/include/mysql -I/Library/Frameworks/Python.framework/Versions/3.5/include/python3.5m -c _mysql.c -o build/temp.macosx-10.6-intel-3.5/_mysql.o -fno-omit-frame-pointer
/usr/bin/clang -bundle -undefined dynamic_lookup -arch i386 -arch x86_64 -g build/temp.macosx-10.6-intel-3.5/_mysql.o -L/usr/local/Cellar/mysql/5.7.16/lib -lmysqlclient -lssl -lcrypto -o build/lib.macosx-10.6-intel-3.5/_mysql.cpython-35m-darwin.so
ld: library not found for -lssl
clang: error: linker command failed with exit code 1 (use -v to see invocation)
error: command '/usr/bin/clang' failed with exit status 1
錯誤出現(xiàn)的系統(tǒng)是 macOS Sierra, 在 EI Capitan 上安裝沒有遇到這個問題乾胶。
問題分析
系統(tǒng)上明明裝了 openssl 庫抖剿,可是為什么找不到 libssl 呢?找了一堆答案都是教大家用 brew link --force openssl
识窿,可是這個方法對 macOS Sierra 無效斩郎。原因是蘋果現(xiàn)在不用 openssl 了,而是使用自己維護的加密算法庫喻频。為什么要這樣做缩宜,不得而知,或許是被 openssl 經常爆出的滴血漏洞傷透了心吧甥温。
所以锻煌,要在 mac 上鏈接 ssl 庫,需要指定庫的路徑姻蚓,即加上 -L/usr/local/opt/openssl
宋梧,把這個目錄加進庫的搜索路徑即可。
細心的人在用 brew install openssl
時會注意到下面的信息:
This formula is keg-only, which means it was not symlinked into /usr/local.
Apple has deprecated use of OpenSSL in favor of its own TLS and crypto libraries
Generally there are no consequences of this for you. If you build your
own software and it requires this formula, you’ll need to add to your
build variables:
LDFLAGS: -L/usr/local/opt/openssl/lib
CPPFLAGS: -I/usr/local/opt/openssl/include
PKG_CONFIG_PATH: /usr/local/opt/openssl/lib/pkgconfig
解決方案
- 從 Github 上下載 mysqlclient 源碼
- 進入項目的 virtualenv 環(huán)境狰挡。為什么要這一步捂龄,因為我們希望把 mysqlclient 安裝到項目所在的 python 運行環(huán)境中
- 運行
python setup.py install
,這個時候肯定還是報錯的 - 拷貝命令臺上的最后一個報錯的命令圆兵,在
-L/usr/local/Cellar/mysql/5.7.16/lib
后面增加如下內容-L/usr/local/opt/openssl
跺讯,然后回車再執(zhí)行一遍這個命令 - 再次運行
python setup.py install
即可成功安裝
當然,這個做法是偷懶的做法殉农。真正優(yōu)雅一點的是修改 mysqlclient 的編譯腳本刀脏,直接把 ssl 庫增加進去〕剩或許還可以向開發(fā)者提個 PR 來解決這個問題愈污。