I have a C++ program that waits for some text input with getline()
, and it works well from the command line.
However, I would like to call it from Python – send some text, get the output, and have it wait for more input.
I tried with subprocess
, but it seems that getline()
in this case doesn’t wait for input but gets an empty line. It works as intended if I constantly send input, but as soon as I stop doing that, it starts reading empty strings.
Adding if (!input_command.empy())
in C++ works, but in this way the program consumes a lot of resources (I suppose because it keeps cycling the loop).
Is it possible to have getline()
stop and wait for some actual input?
C++:
bool ExitProg = FALSE;
do{
string input_command;
getline(cin, input_command)
if (input_command == std::string("something")){
cout << "something" << endl;
}
if (input_command == std::string("exit")){
ExitProg = True;
}
} while (!ExitProg)
Python:
process = subprocess.Popen('c_program.exe', stdin=subproces.PIPE, stdout=subprocess.PIPE)
process.stdin.write('somethingn')
process.stdin.flush()
print(process.stdout.readline())
UPDATE: I assumed that the program was reading empty lines for the following reason. In the C++ program, I split the input line into an array and, when the python code was finished, I was getting an error from the C++ program about an element of the array not existing.
Advertisement
Answer
I created a class and added the start of the subprocess to the __init__
method. The methods of the class are used to interact with the C++ program. At this point however I was still having the same issue.
I solved it by adding a __del__
method that terminates the subprocess.