DEBUG.WIKI
阿里云;从建站到云上业务;云服务器 · 数据库 · 对象存储;查看产品 →
PanstarCloud:部署应用,接入 AI,云服务器与 AI 网关
IPPeak:从目标地区访问网页,住宅代理、SEO 监测、广告验证

pip 安装 C 扩展报错 fatal error: Python.h: No such file or directory 排障

执行 pip install 编译 uWSGI、psycopg2、gevent 时抛出 fatal error: Python.h: No such file or directory。本文解析 C/C++ 扩展编译机理与系统级 python3-dev / python3-devel 头文件安装实战。

在 Linux 服务器或极简 Docker 镜像(如 ubuntu:minimal 或 python:slim)中使用 pip install 安装包含 C/C++ 底层扩展的 Python 库(如 uwsgi、psycopg2、gevent、pycrypto、cffi)时,GCC 编译器在编译源文件时突然中断报错,控制台输出:fatal error: Python.h: No such file or directory,随后提示 compilation terminated. error: command 'gcc' failed with exit status 1。

故障现象与报错信息

执行 pip 安装:

pip install uwsgi

终端编译构建失败输出:

building 'uwsgi' extension
gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -fPIC -I/usr/include/python3.10 -c core/utils.c -o core/utils.o
core/utils.c:1:10: fatal error: Python.h: No such file or directory
    1 | #include <Python.h>
      |          ^~~~~~~~~~
compilation terminated.
error: command '/usr/bin/gcc' failed with exit code 1
[end of output]

note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for uwsgi
ERROR: Could not build wheels for uwsgi, which is required to install pyproject.toml-based projects

根本原因剖析

  1. 缺少 Python 编译头文件(Header Files): 许多高性能 Python 库的核心模块是用 C 语言编写的,在通过源码包(sdist)安装时,必须由本机的 GCC 编译器进行即时编译生成 .so 动态链接库。 编译 C 语言代码必须引入 Python 的 C-API 定义头文件(即 #include <Python.h>)。
  2. 发行版将运行时与开发包默认拆分(Runtime vs Dev Packages): 在各大 Linux 发行版中,通过系统包管理器安装的 python3 软件包仅包含最小化的运行时解释器,并不包含 C 语言开发头文件与静态库。所有的头文件被单独剥离在 python3-dev(Debian/Ubuntu)或 python3-devel(CentOS/RHEL)中。缺少该开发包时,GCC 在标准搜索路径 /usr/include/ 下根本找不到 Python.h。

诊断排查步骤

  1. 检查当前系统的 Python 版本:
python3 --version
# 输出例如:Python 3.10.12
  1. 检查系统是否缺少对应版本的头文件目录:
ls -d /usr/include/python3*

如果提示找不到该目录,即可 100% 确认属于缺少开发头文件包。

解决方案与恢复操作

步骤一:安装对应版本的系统开发包与基础编译工具链

在宿主机上通过系统包管理器安装对应的 dev / devel 开发依赖包:

在 Ubuntu / Debian 环境中:

# 更新源并安装通用编译工具链与 Python 开发包
sudo apt update
sudo apt install -y build-essential python3-dev

若使用的是特定小版本的 Python(如 Python 3.11):

sudo apt install -y python3.11-dev

在 CentOS / RHEL / Rocky Linux 环境中:

# 安装开发工具集与 python3-devel
sudo yum groupinstall -y "Development Tools"
sudo yum install -y python3-devel

在 Alpine Linux 环境中(常见于极简 Docker 镜像):

apk add --no-cache build-base python3-dev

步骤二:重新执行 pip 安装

头文件就绪后,重新执行 pip 命令:

pip install uwsgi

GCC 会顺利引用 /usr/include/python3.10/Python.h 完成编译链接,提示 Successfully installed uwsgi。

方案三:优先选用官方预编译的二进制 Wheel 包(免去编译烦恼)

很多常用库官方提供了预编译好的 wheel(二进制包),无需本地安装任何 GCC 和 Python.h:

以 psycopg2 为例:

  • pip install psycopg2 会尝试在本地编译源码(需要 Python.h 和 libpq-dev);
  • 直接改用预编译包:
pip install psycopg2-binary

秒级完成安装,完全避开任何本地编译报错。