如何在C++程序中设置环境以使Python代码片段能够运行?

4

我在我的主目录下创建了两个文件embed.pyuseEmbed.cpp

embed.py

import os

print os.getcwd()

useEmbed.cpp

  #include <iostream>
  #include "Python.h"
  using namespace std;

  int main()
  {
       Py_Initialize();
       PyRun_SimpleFile("embed.py");
       Py_Finalize();

      return 0;
  }

执行命令 g++ useEmbed.cpp -o useEmbed 时出现 Python.h not found 的错误,下一步该怎么做才能让 .cpp 文件成功编译并返回正确结果呢?请提供有关如何设置环境以使此测试顺利的提示。

谢谢!

更新:感谢 David 和 Alexander 提供的提示。在我的 Fedora Linux 中安装了 python-devel 包后,问题已经解决。

2个回答

3

请确保将编译器指向存放 Python.h 的目录,即使用带有 gcc 的 -I<path> 开关。当然,您需要安装 Python 开发文件。


使用Python源代码目录,使用gcc -I <Include路径/> useEmbed.cpp -o embed命令会返回pyconfig.h未找到的错误。如何处理Python源文件目录? - Jason

3
在Linux上,您可以使用python-config获取编译器标志(python-config --cflags)和链接器标志(python-config --ldflags)。
例如: #> python-config --cflags
-I/usr/include/python2.5 -I/usr/include/python2.5 -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes
#> python-config --ldflags
-L/usr/lib/python2.5/config -lpthread -ldl -lutil -lm -lpython2.5
要编译您的程序,您可以运行以下命令:g++ useEmbed.cpp -o embed "cflags" "ldflags": #> g++ useEmbed.cpp -o embed -I/usr/include/python2.5 -I/usr/include/python2.5 -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -L/usr/lib/python2.5/config -lpthread -ldl -lutil -lm -lpython2.5 我不得不稍微修改useEmbed.cpp:

    #include "Python.h"
    #include <iostream>
using namespace std;
int main() { Py_Initialize(); FILE *file = fopen("embed.py","r+"); PyRun_SimpleFile(file,"embed.py"); Py_Finalize(); fclose(file);
return 0; }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接