Ivan Albert
Ivan Albert

Reputation: 53

How do you run a python script from a C++ program?

I have been able to find out a few things I know that you need to include Python.h and that you need to have

Py_Initialize();
//code that runs the python script
Py_Finalize();

to open and close the interpreter, but that middle part has me lost. Most of the information I can find on the subject use the Py_SimpleString() command with some arguments. I have been searching for a while but I can't find any documentation that clearly explains what that command is doing or how exactly to use it.

I don't necessarily need the python script to directly pass values to the C++ program. It's writing to a text file and the C++ can just parse the text file for the piece it needs. I just need to get the .py file to run and preform its functions.

Any help is appreciated!

Upvotes: 5

Views: 20902

Answers (2)

Jeremy Friesner
Jeremy Friesner

Reputation: 73041

The easiest way to run a Python script from within a C++ program is via PyRun_SimpleString(), as shown in the example at this web page:

#include <Python.h>

int main(int argc, char *argv[])
{
  Py_SetProgramName(argv[0]);  /* optional but recommended */
  Py_Initialize();
  PyRun_SimpleString("from time import time,ctime\n"
                     "print 'Today is',ctime(time())\n");
  Py_Finalize();
  return 0;
}

If you want to run a script that's stored in a .py file instead of supplying the Python source text directly as a string, you can call PyRun_SimpleFile() instead of PyRun_SimpleString().

Upvotes: 11

Related Questions