0

I want my C++ processes to pass their return value to open a python script.

cpp example file

int main()

{
   //do something
   //process is going to finish and is gonna return, for simplicity, 0
   //retval = 0, or whatever the return value is going to be 
   popen("mypython_script.py retval")
   return 0;
}

mypython_script.py

if __name__ == "__main__":
    cpp_retval = sys.argv[1]
    print(cpp_retval)

I don't know if it's possible for the C++ file to send their return value as described, but this is just the general behaviour I want to achieve.

I also have control over the parent process of each C++ process: it's another python script which is in charge of opening C++ files and killing their process if needed, so if you have a solution that involves using the parent process to fetch the return value from "cpp example file", that's more than welcome

EDIT: I forgot to add that I cannot ask the parent python process to wait for the C++ program to return something. In no way I can have "waits" of any sort in my program.

someCoder
  • 185
  • 3
  • 15
  • 1
    Can you use python subprocess? In that case you can check return values easily. See https://stackoverflow.com/questions/9041141/get-a-return-value-using-subprocess. – Mikael H Jun 16 '20 at 10:46

1 Answers1

2

You can capture the return value of the C++ program from the parent python script, if you run the C++ program using cpp_retval = subprocess.call(...), or cpp_retval = subprocesss.run(...).returncode (https://docs.python.org/3/library/subprocess.html).

Then you can pass that to the other python script. So, something like this:

cpp_retval = subprocess.call(["my_cpp_program.exe"])
subprocess.call(["my_python_script.py", str(cpp_retval)])

If you want to directly pass the value from the C++ program to the python script you could do it like this:

#include <cstdlib> // std::system
#include <string>

int main()
{
  const int retval = do_stuff();
  std::system((std::string("my_python_script.py") + ' ' + std::to_string(retval)).c_str());

  return retval;
}
  • The problem I'd have with the subprocess solution in python is that I'd have to wait for the C++ program to finish and I can't either wait because my entire project can't even waste a millisecond neither can I predict whether the program is supposed to return something or not (some of them work indefinitely under a (while True) loop) The C++ solution however seems to be very viable and simple – someCoder Jun 16 '20 at 12:02