如何设置python代码段在c++程序中运行的环境?

2024-10-03 17:14:45 发布

您现在位置:Python中文网/ 问答频道 /正文

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

嵌入.py

import os

print os.getcwd()

使用嵌入.cpp

^{pr2}$

命令g++ useEmbed.cpp -o useEmbed返回Python.h not found,下一步我该怎么做才能使.cpp文件成功编译并返回正确答案?感谢您提供有关如何设置环境以使此测试正常的提示。在

谢谢你!在

更新:感谢大卫和亚历山大的提示。在我的fedoralinux中安装包python-devel后,问题就解决了。在


Tags: 文件pyimport命令osnotembedcpp
2条回答

在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++使用嵌入.cpp-o嵌入“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

我不得不换衣服使用嵌入.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;
    }

确保将编译器指向Python.h所在的目录,也就是说,在gcc中使用-I<path>开关。当然,您需要安装Python开发文件。在

相关问题 更多 >