今天在搭建Django+mysql環境的時候遇到了一點問題,記錄下來。
安裝環境:OS X 10.10操作系統,Python 2.7。
MySQLdb其實包含在MySQL-python包中,因此無論下載還是在pip中search,都應該是搜尋MySQL-python。
以下將說明MySQLdb兩種常見的安裝方式:
下載安裝或者pip安裝MySQL-python。
源碼安裝
下載MySQLdb源碼
下面是1.2.5的版本
下載后解壓,然后在終端Terminal中執行以下命令:
$ cd MySQL-python-1.2.5
然后修改 site.cfg, 修改下面內容:
由#mysql_config = /usr/local/bin/mysql_config
改成mysql_config = /usr/local/mysql/bin/mysql_config
否則會出現找不到 MySQL config 的問題:
File "/tmp/easy_install-nHSsgl/MySQL-python-1.2.2/setup_posix.py", line 24, in mysql_config
EnvironmentError: mysql_config not found
然后修改 _mysql.c, 把第 37 到 39 行注釋掉, 如下:
//#ifndef uint //#define uint unsigned int //#endif
否則會出現:
In file included from /usr/local/mysql/include/mysql.h:47,
from _mysql.c:40:
/usr/include/sys/types.h:92: error: duplicate 'unsigned'
/usr/include/sys/types.h:92: error: two or more data types in declaration specifiers
error: command 'gcc' failed with exit status 1
然后再用 python ./setup.py build 編譯
$ python ./setup.py build
然后再用 python ./setup.py install 安裝
$ sudo python ./setup.py install Password:
使用pip安裝MySQLdb
在終端中執行:$ pip install MySQL-python
使用pip安裝時沒有辦法修改site.cfg文件,因此可以通過修改OS X的系統環境變量來解決找不到mysql_config的錯誤。
修改OS X環境變量:打開終端,在終端中使用vim打開“~/.bash_profile”,如果沒有安裝vim,那就顯示隱藏文件用文本編輯器打開,具體操作這里就不復述了。在.bash_profile中添加以下內容:
PATH="/usr/local/mysql/bin:${PATH}"
export PATH
export DYLD_LIBRARY_PATH=/usr/local/mysql/lib/
export VERSIONER_PYTHON_PREFER_64_BIT=no
export VERSIONER_PYTHON_PREFER_32_BIT=yes
其中 VERSIONER_PYTHON_PREFER_64_BIT和VERSIONER_PYTHON_PREFER_64_BIT根據自己安裝的MySQL進行選擇。
另外再提供一個pip安裝時找不到mysql_config的解決方法,在終端中輸入以下命令:
$ sudo ln -s /usr/local/mysql/bin/* /usr/bin
到這里,MySQL-python包應該基本順利安裝。
解決 Reason: image not found 錯誤
安裝完MySQL-python包后,讓我們import MySQLdb,此時出現一個錯誤,錯誤最后一行寫着 Reason: image not found。
解決方法是在終端執行:
$ sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib
$ sudo ln -s /usr/local/mysql/lib /usr/local/mysql/lib/mysql
測試
用下面的命令進行測試:
$ cd ~ $ python Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import MySQLdb >>> MySQLdb.apilevel '2.0' >>> import django >>> print django.VERSION (1, 0, 'final')
常見錯誤
clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future]
clang: note: this will be a hard error (cannot be downgraded to a warning) in the future
經網上查證:http://www.tuicool.com/articles/zI7Vzu,貌似是mac os的Xcode從5.1起給編譯器規定對於未知參數傳入視為error,我們需要使用ARCHFLAGS將該error降級為warning,因此最后的安裝命令應該如下:
sudo ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future python setup.py build
