Communicate with subprocess in Ruby

2019-08-09 17:05发布

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.

1条回答
倾城 Initia
2楼-- · 2019-08-09 17:49

The code you wrote works for me with the cat program:

IO.popen("cat", "r+") do |io|
  io.puts("abcdef\n")
  answer1 = io.gets
  puts answer1
  io.puts("#{answer1.chomp}ghijkl\n")
  answer2 = io.gets
  puts answer2
end

This prints

abcdef
abcdefghijkl

Maybe you need to flush your io after puts?

查看更多
登录 后发表回答