Embedding a Python CLI into a C++ program

67 views Asked by At

I am working on a larger C++ codebase and I want to add a Python CLI to it, for example for testing purposes. For that I want to expose some C++ functions to python to interact with my system. The thing is, my C++ program is running at the same time that I want my python shell to be active, sucht that I could for example send some events into the system and get an answer back. I've gone down on a google hut but all I can find is either how to compile C/C++ code to be a python module, or how to call python code from within C/C++. I've yet to find a solution or any examples on how to have a python CLI on an active system.

So far the only thing that kind of resembles what I want to do is the PyRun_InteractiveLoop command. With that I at least got a python CLI running while my C++ code is running. I also found several examples on how to make C++ code callable from python as a module. The Problem is, that I can't find a way to get both of these things at once.

1

There are 1 answers

0
Raj Maddheshiya On

-You can run Python code using the PyRun_SimpleString function or by loading a Python script.

-Include the necessary headers for both C++ and Python. For C++, include or any other headers you need. For Python, include Python.h.

 #include <iostream>
 #include <Python.h>


 int main(int argc, char* argv[]) {
    Py_Initialize();

    // Run a Python command
    PyRun_SimpleString("print('Hello from Python!')");

    Py_Finalize();
    return 0;
 }