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.
1 Answer 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
cpinstead of trying to be clever?