Does anybody know how to start a subprocess in Ruby and communicate with it using the stdin and stdout of the started subprocess? Something like the following:
IO.popen("subprocess", "r+") do |io|
io.puts(question1)
answer1 = io.gets
question2 = follow_up_question(question1, answer1)
io.puts(question2)
answer2 = io.gets
# etc
end
The key point is that I want to do interaction. I don't want to just send all the input for the started program and then retrieve all the output, but I want to send stuff and receive answers subsequently. Is there any way to do it? I tried IO.popen, Open3.popen2 and about 10 other methods, but all of them expect that you send all the input for the subprocess first and then retrieve all the output. I found no method for interaction.
The code you wrote works for me with the
cat
program:This prints
Maybe you need to flush your
io
afterputs
?