How can I pass variables from Python back to C++?

0

Issue

I have 2 files – a .cpp file and a .py file. I use system("python something.py"); to run the .py file and it has to get some input. How do I pass the input back to the .cpp file? I don’t use the Python.h library, I have two separate files.

Solution

system() is a very blunt hammer and doesn’t support much in the way of interaction between the parent and the child process.

If you want to pass information from the Python script back to the C++ parent process, I’d suggest having the python script print() to stdout the information you want to send back to C++, and have the C++ program parse the python script’s stdout-output. system() won’t let you do that, but you can use popen() instead, like this:

#include <stdio.h>

int main(int, char **)
{
   FILE * fpIn = popen("python something.py", "r");
   if (fpIn)
   {
      char buf[1024];
      while(fgets(buf, sizeof(buf), fpIn))
      {
         printf("The python script printed:  [%s]\n", buf);
     
         // Code to parse out values from the text in (buf) could go here
      }
      pclose(fpIn);  // note:  be sure to call pclose(), *not* fclose()
   }
   else printf("Couldn't run python script!\n");

   return 0;
}

If you want to get more elaborate than that, you’d probably need to embed a Python interpreter into your C++ program and then you’d be able to call the Python functions directly and get back their return values as Python objects, but that’s a fairly major undertaking which I’m guessing you want to avoid.

Answered By – Jeremy Friesner

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More