Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

python

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!

like image 993
Ivan Albert Avatar asked May 23 '16 20:05

Ivan Albert


People also ask

How do you call a Python script from C program?

Create the return value, Restore previous GIL state and return. A reference to an existing Python callable needs to be passed in, to use this function. To do that there are many ways like – simply writing C code to extract a symbol from an existing module or having a callable object passed into an extension module.

Can you use Python in C?

To write Python modules in C, you'll need to use the Python API, which defines the various functions, macros, and variables that allow the Python interpreter to call your C code. All of these tools and more are collectively bundled in the Python. h header file.

How do I connect Python to C?

The rawest, simplest way is to use the Python C API and write a wrapper for your C library which can be called from Python. This ties your module to CPython. The second way is to use ctypes which is an FFI for Python that allows you to load and call functions in C libraries directly.

How do you call a Python file from C++?

std::string filename = "/home/abc/xyz/script.py"; std::string command = "python "; command += filename; system(command. c_str()); This does call and execute the python script. The print commands in the Python are being executed.


1 Answers

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

like image 193
Jeremy Friesner Avatar answered Nov 12 '22 05:11

Jeremy Friesner