我试图使用C扩展名文件构建共享库,但首先必须使用以下命令生成输出文件:
gcc -Wall utilsmodule.c -o Utilc
执行命令后,我收到以下错误消息:
> utilsmodule.c:1:20: fatal error: Python.h: No such file or directory
compilation terminated.
我已经在互联网上尝试了所有建议的解决方案,但问题仍然存在。我对Python.h没有问题。我设法在我的机器上找到了该文件。
我试图使用C扩展名文件构建共享库,但首先必须使用以下命令生成输出文件:
gcc -Wall utilsmodule.c -o Utilc
执行命令后,我收到以下错误消息:
> utilsmodule.c:1:20: fatal error: Python.h: No such file or directory
compilation terminated.
我已经在互联网上尝试了所有建议的解决方案,但问题仍然存在。我对Python.h没有问题。我设法在我的机器上找到了该文件。
当前回答
你必须做两件事。
安装Python开发包,如果是Debian/Uubuntu/Mint,可以使用以下命令完成:
sudo apt-get install python-dev
第二点是,默认情况下,include文件不在include路径中,Python库默认情况下也不与可执行文件链接。您需要添加这些标志(相应地替换Python的版本):
-I/usr/include/python2.7 -lpython2.7
换句话说,编译命令应该是:
gcc -Wall -I/usr/include/python2.7 -lpython2.7 utilsmodule.c -o Utilc
其他回答
这里还有另一个解决方案,因为这些解决方案都不适合我。作为参考,我试图在AmazonLinuxAMI基础Docker镜像上安装Python 3.6的一些东西。
非码头解决方案:
# Install python3-devel like everyone says
yum -y install python36-devel.x86_64
# Find the install directory of `Python.h`
rpm -ql python36-devel.x86_64 | grep -i "Python.h"
# Forcefully add it to your include path
C_INCLUDE_PATH='/usr/include/python3.6m'
export C_INCLUDE_PATH
Docker解决方案:
# Install python3-devel like everyone says
RUN yum -y install python36-devel.x86_64
# Find the install directory of `Python.h`, for me it was /usr/include/python3.6m
RUN rpm -ql python36-devel.x86_64 | grep -i "Python.h" && fake_command_so_docker_fails_and_shows_us_the_output
# Since the previous command contains a purposeful error, remove it before the next run
# Forcefully add it to your include path
ARG C_INCLUDE_PATH='/usr/include/python3.6m'
注意:如果在编译C++时遇到错误,请使用CPLUS_INCLUDE_PATH。
或者,您可能更喜欢使用另一个Docker映像。例如,我试图在python:3.9.4-slim上安装asyncpg~=0.24.0,这产生了与您看到的相同的错误。然而,当我将图像更新为python:3时,它工作得很好。
确保Python开发文件随操作系统一起提供。
您不应该硬编码库和包含路径。相反,使用pkg配置,它将为您的特定系统输出正确的选项:
$ pkg-config --cflags --libs python2
-I/usr/include/python2.7 -lpython2.7
您可以将其添加到gcc行:
gcc -Wall utilsmodule.c -o Utilc $(pkg-config --cflags --libs python2)
对我来说,把它改成这个效果很好:
#include <python2.7/Python.h>
我找到了文件/usr/include/python2.7/Python.h,因为/usr/include已经在include路径中,所以python2.7/Python.h应该就足够了。
您还可以从命令行添加include路径,而不是-gcc-I/usr/lib/python2.7(谢谢@erm3nda)。
有时,即使在安装python dev之后,错误仍然存在,如果缺少“gcc”,请检查错误。
第一次下载,如中所述https://stackoverflow.com/a/21530768/8687063,然后安装gcc
对于apt(Ubuntu、Debian…):
sudo apt-get install gcc
对于yum(CentOS,RHEL…):
sudo yum install gcc
对于dnf(Fedora…):
sudo dnf install gcc
对于zypper(openSUSE…):
sudo zypper in gcc
对于apk(Alpine…):
sudo apk gcc
如果您使用tox在多个版本的Python上运行测试,则可能需要为正在测试的每个版本的Python安装Python开发库。
sudo apt-get install python2.6-dev
sudo apt-get install python2.7-dev
etc.