Search code examples
pythonc++raspberry-pi3

How can I get a variable's value from a Python script in C++?


so my problem is I have a Python script which reads datas from a sensor, at the end i want these datas to get into a string in the C++ code.

I have tried installing boost.python but didn't work. (The installation it self have failed, so im looking for a new option)

Basicly the question is:

I have a script like this:

def sum():
    string = "whateverdata"     // the data got read in
    return string

sum()

And i want to use it this way:


#include <string>

int main()
{
   string data = ???        // idk how 

  // processing the string  

   return 0;
}

Solution

  • I don't think you can do that. At least, I've never seen it personally.

    I would see if you can do this either all in python, or all in c++.

    If not, try bundling your python file into an exe using pyinstaller, and then making a system call to the python script from c++. It would look something like:

    system("/path/to/pythonexe arg1 arg2");

    To get the information into c++, you could have the python script continuously writing it to a text file, and the c++ program could read that same text file.

    Alternatively, you could have the python script print the sensor data to the stdout and then read that into a buffer in c++. See this implementation for more details.

    Let me know if you have any questions, good luck!