有人知道如何在Ruby中启动子进程并使用启动子进程的stdin和stdout与之通信吗?如下所示:
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
关键是我想做互动。我不想只发送启动程序的所有输入,然后检索所有输出,但我想发送东西并随后收到答案。有什么办法吗?我尝试了IO.popen,Open3.popen2和大约10种其他方法,但它们都希望您先发送子进程的所有输入,然后检索所有输出。我找不到交互方法。
您编写的代码适用于cat
程序:
IO.popen("cat", "r+") do |io|
io.puts("abcdefn")
answer1 = io.gets
puts answer1
io.puts("#{answer1.chomp}ghijkln")
answer2 = io.gets
puts answer2
end
这打印
abcdef
abcdefghijkl
也许您需要在puts
后冲洗io
?