如何使用嵌入式python脚本编译和运行C代码?

Nik*_*las 1 c python

我正在使用python 文档中的这个例子

#include <Python.h>
int
main(int argc, char *argv[])
{
  Py_SetProgramName(argv[0]);  /* optional but recommended */
  Py_Initialize();
  PyRun_SimpleString("from time import time,ctime\n"
                     "print('Today is', ctime(time()))\n");
  Py_Finalize();
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

其中 python 脚本被硬编码为 C 程序。但是当我尝试编译它时

$ gcc -c modwithpy.c -o mod
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:

modwithpy.c:1:20: 致命错误: Python.h: 没有这样的文件或目录编译终止。

但是,我已经安装了python-dev包。我还查看了编译和链接文档,但不明白我需要编写的 python 包的绝对路径。

$ whereis python
python: /usr/bin/python3.3m /usr/bin/python /usr/bin/python2.7-config 
/usr/bin/python3.3 /usr/bin/python2.7 /etc/python /etc/python3.3 /etc/python2.7
/usr/lib/python2.6 /usr/lib/python3.3 /usr/lib/python2.7 /usr/bin/X11/python3.3m
/usr/bin/X11/python /usr/bin/X11/python2.7-config /usr/bin/X11/python3.3
/usr/bin/X11/python2.7 /usr/local/lib/python3.3 /usr/local/lib/python2.7
/usr/include/python2.7 /usr/share/python /usr/share/man/man1/python.1.gz
Run Code Online (Sandbox Code Playgroud)

Gen*_*ene 5

你读得还不够远。此处的文档显示了如何告诉编译器 python 头文件和库所在的位置。

基于此,尝试

gcc `/opt/bin/python3.3-config --cflags` modwithpy.c -o mod \
  `/opt/bin/python3.3-config --ldlags`
Run Code Online (Sandbox Code Playgroud)

如果您python在不同的地方安装的脚本,你将不得不改变/opt/bin到的地方...-config,真是位置。从你的whereis踪迹来看,它可能是/usr/bin.