如何在Mac OSX的Python虚拟环境中获取python.h?

9 投票
3 回答
9211 浏览
提问于 2025-04-18 10:55

我正在为一个Python应用写一个C扩展,需要测试一些特定于Python的C代码。为此,我需要在我的C文件中导入Python.h,但我一直没能做到这一点。大多数教程建议使用类似于sudo apt-get python-dev的命令,但我的系统没有apt-get,就算有,我觉得把开发文件放在我的虚拟环境中会更好。

有没有什么办法可以把Python.h放到我的虚拟环境里?

3 个回答

3

假设你是在使用MacOSX,并且通过homebrew安装了Python,

terminal(终端)中,你可以用以下命令找到Python.h文件:

find /usr/local/Cellar/ -name Python.h

这个命令在我的系统上返回了:

/usr/local/Cellar//python/2.7.6/Frameworks/Python.framework/Versions/2.7/include/python2.7/Python.h
4

在终端中,

$python-config --includes
10

设置环境变量 C_INCLUDE_PATH,以便包含你的 Python 安装目录。

举个例子:

1. 获取你 Python 安装的包含目录。

    find /usr/local/Cellar/ -name Python.h

这会返回类似这样的内容:

    /usr/local/Cellar//python3/3.6.3/Frameworks/Python.framework/Versions/3.6/include/python3.6m/Python.h

现在设置你的 C_INCLUDE_PATH 变量:

    export C_INCLUDE_PATH="/usr/local/Cellar//python3/3.6.3/Frameworks/Python.framework/Versions/3.6/include/python3.6m/"

撰写回答