无法安装MySQLdb的一个解决办法

由于项目(前人代码)需求,需要使用 python2 + MySQLdb,但在安装 MySQLdb的时候出错。

现将错误及解决办法记录如下。

  1. 习惯性使用 conda 安装:
1
2
3
4
5
6
7
8
9
10
11
$ conda install MySQLdb
Fetching package metadata .........................

PackageNotFoundError: Packages missing in current channels:

- mysqldb
We have searched for the packages in the following channels:

- https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
- https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/
 - ......

我一开始只是简单地以为是 conda 仓库没有包含这个包。

  1. 使用 pip2 安装
1
2
3
4
$ pip2 install MySQLdb # MySQLdb不支持python3
Collecting MySQLdb
Could not find a version that satisfies the requirement MySQLdb (from versions: )
No matching distribution found for MySQLdb

这下子问题就大了,毕竟 MySQLdb 停止更新太久了,于是上 PyPI 搜了一下,果不其然,找不到这个包了。在宁桑的指导下,转战 Github,找到了提供相同接口的包 mysqlclient,开心,直接找到 #install-from-pypi 按照文档一顿操作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$ pip install mysqlclient
Collecting mysqlclient
 Downloading ……
Complete output from command python setup.py egg_info:
sh: 1: mysql_config: not found
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/tmp/pip-build-VJVKuw/mysqlclient/setup.py", line 17, in <module>
metadata, options = get_config()
File "/tmp/pip-build-VJVKuw/mysqlclient/setup_posix.py", line 44, in get_config
libs = mysql_config("libs_r")
File "/tmp/pip-build-VJVKuw/mysqlclient/setup_posix.py", line 26, in mysql_config
raise EnvironmentError("%s not found" % (mysql_config.path,))
EnvironmentError: mysql_config not found

----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-VJVKuw/mysqlclient/

没想到吧.jpg

试了一下:

1
2
3
$ mysql_config
The program 'mysql_config' is currently not installed. You can install it by typing:
sudo apt install libmysqlclient-dev

很好,装上 libmysqlclient-dev 之后一切顺利,问题不大。结果发现,人家 mysqlclient 的文档里面还有一个 #Prerequisites ,里面写了一句这样的话:

You may need to install the Python and MySQL development headers and libraries like so:

  • sudo apt-get install python-dev libmysqlclient-dev # Debian / Ubuntu

行吧。

mysqlclient 甚至提供了对 python3 的支持。