我试图使用C扩展名文件构建共享库,但首先必须使用以下命令生成输出文件:

gcc -Wall utilsmodule.c -o Utilc

执行命令后,我收到以下错误消息:

> utilsmodule.c:1:20: fatal error: Python.h: No such file or directory
compilation terminated.

我已经在互联网上尝试了所有建议的解决方案,但问题仍然存在。我对Python.h没有问题。我设法在我的机器上找到了该文件。


当前回答

这里还有另一个解决方案,因为这些解决方案都不适合我。作为参考,我试图在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时,它工作得很好。

其他回答

我设法解决了这个问题,并在一个命令中生成.so文件

gcc -shared -o UtilcS.so
-fPIC -I/usr/include/python2.7 -lpython2.7  utilsmodule.c

当然,python-dev或libpython-all-dev是(apt)安装的第一件事,但如果这对我的情况没有帮助,我建议您通过sudo apt-get-install libffi-dev和sudo pip-install cffi安装外部函数接口包。

这将有助于解决问题,尤其是当您看到错误为/from c/_cffi_backend.c:2:20:致命错误:Python.h:没有这样的文件或目录时。

有时,即使在安装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

我在ubuntu中安装coolprop时也遇到了这个错误。

对于ubuntu 16.04和python 3.6

sudo apt-get install python3.6-dev

如果这不起作用,请尝试安装/更新gcc-lib。

sudo apt-get install gcc

尝试apt文件。很难记住丢失文件所在的包名。它是通用的,适用于任何包文件。

例如:

root@ubuntu234:~/auto# apt-file search --regexp '/Python.h$'
pypy-dev: /usr/lib/pypy/include/Python.h
python2.7-dbg: /usr/include/python2.7_d/Python.h
python2.7-dev: /usr/include/python2.7/Python.h
python3.2-dbg: /usr/include/python3.2dmu/Python.h
python3.2-dev: /usr/include/python3.2mu/Python.h
root@ubuntu234:~/auto# 

现在你可以做出专家猜测,从中选择哪一个。