从C ++代码运行的Python文件

时间:2016-07-15 11:50:39

标签: python python-2.7 python-3.x

我正在使用Python 3.3。 我正在使用C ++ Qt代码并将python嵌入其中。我想在Python 3中使用C Python API执行一个python文件。

下面是我用来读取文件并使用Qt执行的示例代码。

FILE *cp = fopen("/tmp/my_python.py", "r");
if (!cp)
{        
    return;
}

Py_Initialize();

// Run the python file
#ifdef PYTHON2
PyObject* PyFileObject = PyFile_FromString("/tmp/my_python.py", (char *)"r");
if (PyRun_SimpleFile(PyFile_AsFile(PyFileObject), "/tmp/my_python.py") != 0)
    setError(tr("Failed to launch the application server, server thread exiting."));

#else
int fd = fileno(cp);
PyObject* PyFileObject = PyFile_FromFd(fd, "/tmp/my_python.py", (char *)"r", -1, NULL, NULL,NULL,1);
if (PyRun_SimpleFile(fdopen(PyObject_AsFileDescriptor(PyFileObject),"r"), "/tmp/my_python.py") != 0)
    setError(tr("Failed to launch the application server, server thread exiting."));
#endif
Py_Finalize();

对于Python2,一切正常。但是对于python3(#else部分)不能在windows下工作。应用程序正在崩溃。我不想逐行阅读并执行。

有人能指导我如何使用Python3在C ++应用程序中执行python文件吗?一些伪代码或链接会有所帮助。

先谢谢。

1 个答案:

答案 0 :(得分:1)

以下测试程序可以正常地将FILE指针直接传递给我。

<强> runpy.c

#include <stdio.h>
#include <Python.h>

int main(int argc, char** argv)
{
  if (argc != 2)
  {
    printf("Usage: %s FILENAME\n", argv[0]);
    return 1;
  }
  FILE* cp = fopen(argv[1], "r");
  if (!cp)
  {
    printf("Error opening file: %s\n", argv[1]);
    return 1;
  }

  Py_Initialize();

  int rc = PyRun_SimpleFile(cp, argv[1]);
  fclose(cp);

  Py_Finalize();  
  return rc;
}

在Fedora 23上编译:

g++ -W -Wall -Wextra -I/usr/include/python3.4m -o runpy runpy.c -lpython3.4m