0

I am using Python 3.3. I am using C++ Qt code and embedding python into it. I want to execute one python file using C Python API in Python 3.

Below is sample code i am using to read the file and execute using 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();

For Python2 everything is working fine. But for python3(#else part) is not working under windows. Application is getting crashed. I do not want to read line by line and execute.

Can anyone give me guidance how to execute python file in C++ application using Python3 ? Some pseudo code or link will be helpful.

Thanks in Advance.

3
  • Why are you not just passing cp instead of trying to be clever? Commented Jul 15, 2016 at 11:55
  • You mean to say to call "if (PyRun_SimpleFile(cp, "/tmp/my_python.py")) right? This also i have tried but same result. Commented Jul 15, 2016 at 11:57
  • docs.python.org/3/c-api/veryhigh.html#c.PyRun_SimpleFile Commented Jul 15, 2016 at 11:58

1 Answer 1

1

The following test program works fine passing the FILE pointer in directly for me.

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;
}

Compiled on Fedora 23 with:

g++ -W -Wall -Wextra -I/usr/include/python3.4m -o runpy runpy.c -lpython3.4m
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.