Python初学,要连接到数据库MySQL,需要安装接口程序: MySQL-Python (即:MySQLdb模块)
因用的Mac电脑,安装过程颇费一番波折,在Google大神的辅导下终于搞定,特此记录以总结经验:
环境说明:
系统:MacOS 10.11
Python:系统自带的2.7.10
-
第1步:下载MySQL-Python,并解压
下载地址:从sourceforge下载插曲说明:
sourceforge站点牛逼的做了系统识别,
如果是Mac系统则下载的包为.tar的压缩包,下载后解压即可;
如果是Win系统则下载的是exe的安装包;
惭愧,在这点上吃了大亏,当时不知道是系统哪里出了错,硬是只给我下载exe包,折腾了半天,最后还是到GitHub上MySQLdb源下载了源代码包来安装的 -
第2步:修改site.cfg文件
解压MySQL-Python后,按理应该直接运行安装,可是如果直接用第3步的安装,会出现mysql_config not found错误,要解决这个错误,在MySQL-python的安装包中找到site.cfg文件,打开它,找到以下内容:# The path to mysql_config. # Only use this if mysql_config is not on yourPATH, or you have some weird # setup that requires it. # mysql_config = /usr/local/bin/mysql_config
上文最后一句代码指示的是
mysql_config
的地址,默认是屏蔽的状态;
去掉这一句前面的#
,并将mysql_config
地址改为/usr/local/mysql/bin/mysql_config
,因为这是mysql_config
默认的真实地址(mac安装mysql默认这个地址下有mysql_config
文件,想确认的朋友可以Shift+Command+G
前往这个目录查看),代码改后如下:mysql_config = /usr/local/mysql/bin/mysql_config
-
第2步:安装python
运行终端(Terminal)程序,在窗口中执行:$ python setup.py install
运行安装程序并提示成功后,MySQL-Python就安装成功了,这个时候可在终端窗口验证:
$ Python $ import MySQLdb
若没有提示错误,即安装成功!
-
报错说明:网上教程里说会遇到 Reason: image not found 的错误,(如果你遇到可以百度下解决方案),我没有遇到这个报错,不过却遇到另一个报错:
error: can't create or remove files in install directory The following error occurred while trying to add or remove files in theinstallation directory: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/test-easy-install-3121.write-test' The installation directory you specified (via --install-dir, --prefix, orthe distutils default setting) was: /Library/Python/2.7/site-packages/ Perhaps your account does not have write access to this directory? If theinstallation directory is a system-owned directory, you may need to sign inas the administrator or "root" account. If you do not have administrativeaccess to this machine, you may wish to choose a different installationdirectory, preferably one that is listed in your PYTHONPATH environmentvariable. For information on other options, you may wish to consult thedocumentation at: http://packages.python.org/distribute/easy_install.html Please make the appropriate changes for your system and try again.
经过百度后,终于知道原因,将命令改为:
sudo python setup.py install
然后输入密码,这样就安装成功了!
参考来源:Strack overflow: Python - [Errno 13] Permission denied
额外收获:知道了Python和MySQL的安装地址
Python:/usr/bin/python
MySQL:/usr/local/mysql/
想确认的朋友可以Shift+Command+G
前往这个目录查看
作者:大数据社区
链接:http://www.jianshu.com/p/71cf187598ce
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。