MySQLdb unter Mac OS X „Snow Leopard“

Wenn man unter Mac OS X MySQLdb bauen will, und einen Intel-Mac mit Snow Leopard zusammen mit XCode 4 betreibt, muss man einige Hürden umschiffen.

1.    Man muss darauf achten, dass Python und MySQL in der gleichen Architektur vorliegen (entweder i386 oder x86_64)
2.    MySQL-python herunterladen und auspacken (http://pypi.python.org/pypi/MySQL-python/)
3.    Im Default ist das Compile-Target von XCode 10.3. Das funktioniert nicht!
⁃    export ARCHFLAGS=‘-arch x86_64′
⁃    export MACOSX_DEPLOYMENT_TARGET=10.6
4.    Jetzt kann man, wie üblich, mit python setup.py build und python setup.py install das Paket MySQLdb bauen (siehe README).

Allerdings funktioniert es noch nicht, wenn man versucht, das Modul zu importieren, so wird man mit folgender Fehlermeldung belohnt:

Python 2.7.1 (r271:86882M, Nov 30 2010, 10:35:34)
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type „help“, „copyright“, „credits“ or „license“ for more information.
>>> import MySQLdb
Traceback (most recent call last):
File „<stdin>“, line 1, in <module>
File „build/bdist.macosx-10.6-intel/egg/MySQLdb/__init__.py“, line 19, in <module>
File „build/bdist.macosx-10.6-intel/egg/_mysql.py“, line 7, in <module>
File „build/bdist.macosx-10.6-intel/egg/_mysql.py“, line 6, in __bootstrap__
ImportError: dlopen(/Users/hl/.python-eggs/MySQL_python-1.2.3-py2.7-macosx-10.6-intel.egg-tmp/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib
Referenced from: /Users/hl/.python-eggs/MySQL_python-1.2.3-py2.7-macosx-10.6-intel.egg-tmp/_mysql.so
Reason: image not found

Entweder liest man hier wirklich mal die Fehlermeldung durch, oder man sucht eben solange, bis man den Fehler hat (wie ich 🙂 )

Hintergrund ist, dass das libtool für die Bibliothek libmysqlclient.18.dylib keinen Pfad in der _mysql.o hinterlegt:

$ otool -L _mysql.so
_mysql.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 125.2.10)

Die Lösung des ganzen ist relativ simpel;

entweder den Suchpfad anpassen:
$ export DYLD_LIBRARY_PATH=/usr/local/mysql/lib:$DYLD_LIBRARY_PATH

oder die Dylib fixen (eine Zeile!):
$ install_name_tool -change libmysqlclient.18.dylib /usr/local/mysql/lib/libmysqlclient.18.dylib _mysql.so

Danach klappt auch der Modulimport 🙂