This may be easy but I couldn't find the solution anywhere, so sorry.
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.
Thanks in advance!
CodePudding user response:
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.