5

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!

asked May 23, 2016 at 20:26

2 Answers 2

11

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().

Ajax1234
71.7k9 gold badges67 silver badges110 bronze badges
answered May 23, 2016 at 20:45
Sign up to request clarification or add additional context in comments.

1 Comment

You'll need to have the Python library linked in to your application for it to work. Assuming you have that, you don't need to have Python installed separately on the computer, since it will use the Python interpreter that is built in to your app's executable file. (You will need to have any .py files you want to import present in a folder in the Python load-path, though)
0
answered May 23, 2016 at 20:40

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.