macOS安装lxml报错'Python.h' file not found

背景

macOS环境:Ventura 13.0 (Apple Silicon)

Python版本:3.9.6

lxml是笔者常用的html内容解析库。但笔者在macOS上安装lxml时碰到了如下报错:

1
pip3 install lxml
1
2
3
4
5
...
src/lxml/etree.c:96:10: fatal error: 'Python.h' file not found
#include "Python.h"
^~~~~~~~~~
...

这篇文章简单记录下解决方案。

解决方案

  1. 找到Python.h文件所处位置:

    1
    sudo find / -iname "Python.h"
    1
    2
    3
    4
    5
    ...
    /Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/Headers/Python.h
    /Library/umad/Python.framework/Versions/3.8/include/python3.8/Python.h
    /Library/Crypt/Python.framework/Versions/3.8/include/python3.8/Python.h
    ...
  2. 笔者使用的Python版本为3.9,将对应版本的文件夹设置到环境变量中:

    1
    export C_INCLUDE_PATH=/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/Headers/
  3. 重新安装,搞定

    1
    2
    3
    4
    ...
    Successfully built lxml
    Installing collected packages: lxml
    Successfully installed lxml-4.9.2

引用

macos - fatal error: ‘Python.h’ file not found while installing opencv - Stack Overflow


macOS安装lxml报错'Python.h' file not found
https://www.yooo.ltd/2023/01/16/install-lxml-on-mac/
作者
OrangeWolf
发布于
2023年1月16日
许可协议