python mysqlclient安装指引

1,111 阅读2分钟

安装失败,如何解决

一般来说,安装mysqlclient只需要执行

pip install mysqlclient

但是我失败了:

Collecting mysqlclient

  Using cached mysqlclient-2.2.5.tar.gz (90 kB)

  Installing build dependencies ... done

  Getting requirements to build wheel ... error

  error: subprocess-exited-with-error

  

  × Getting requirements to build wheel did not run successfully.

  │ exit code: 1

  ╰─> [35 lines of output]

      /bin/sh: pkg-config: command not found

      /bin/sh: pkg-config: command not found

      /bin/sh: pkg-config: command not found

      /bin/sh: pkg-config: command not found

      Trying pkg-config --exists mysqlclient

      Command 'pkg-config --exists mysqlclient' returned non-zero exit status 127.

      Trying pkg-config --exists mariadb

      Command 'pkg-config --exists mariadb' returned non-zero exit status 127.

      Trying pkg-config --exists libmariadb

      Command 'pkg-config --exists libmariadb' returned non-zero exit status 127.

      Trying pkg-config --exists perconaserverclient

这个错误通常是由于缺少 pkg-config 工具引起的,pkg-config 用于检测系统中是否安装了必要的库。以下是解决方案:

1. 安装 pkg-config 和 MySQL 开发库

在 macOS 上

使用 Homebrew 安装 pkg-config 和 MySQL 的客户端库:

brew install pkg-config
brew install mysql-client

安装 MySQL 客户端后,还需要将 MySQL 的库路径添加到环境变量中:

export PATH="/opt/homebrew/opt/mysql-client/bin:$PATH"
export LDFLAGS="-L/opt/homebrew/opt/mysql-client/lib"
export CPPFLAGS="-I/opt/homebrew/opt/mysql-client/include"
export PKG_CONFIG_PATH="/opt/homebrew/opt/mysql-client/lib/pkgconfig"

然后就可以成功在python 虚拟环境中安装mysqlclient了

原因

Python 虚拟环境中的 mysqlclient:依赖于系统层面的库来完成底层数据库操作。虚拟环境中的 mysqlclient 只是一个 Python 封装层,并不包含底层的 MySQL 驱动库。本质上它是用来调用我们系统层面的mysql驱动。

系统层面的 MySQL 客户端库:为 mysqlclient 提供核心的连接和操作库(例如 libmysqlclient)。当 Python 虚拟环境中的 mysqlclient 安装时,它会通过 pkg-config 检查系统中是否存在这些库。

所以我们需要先安装pkg-config和mysql-client