我在用Open3's popen3启动一个在类似控制台/中运行的进程的方法REPL重复接受输入并返回输出的时尚。
我可以使用如下代码打开进程、发送输入并接收输出:
Open3.popen3("console_REPL_process") do |stdin, stdout, stderr, wait_thr|
stdin.puts "a string of input"
stdin.close_write
stdout.each_line { |line| puts line } #successfully prints all the output
end
我想连续多次这样做,而不重新打开该进程,因为启动需要很长时间。
我知道我必须关闭标准输入才能让标准输出返回..但我不知道的是,如何“重新打开”标准输入以便可以写入更多输入?
理想情况下我想做这样的事情:
Open3.popen3("console_REPL_process") do |stdin, stdout, stderr, wait_thr|
stdin.puts "a string of input"
stdin.close_write
stdout.each_line { |line| puts line }
stdin.reopen_somehow()
stdin.puts "another string of input"
stdin.close_write
stdout.each_line { |line| puts line }
# etc..
end
solution
感谢 pmoo 的回答,我能够使用以下方法设计一个解决方案PTY
and expect
,期望进程在准备好更多输入时返回提示字符串,如下所示:
PTY.spawn("console_REPL_process") do |output, input|
output.expect("prompt >") do |result|
input.puts "string of input"
end
output.expect("prompt >") do |result|
puts result
input.puts "another string of input"
end
output.expect("prompt >") do |result|
puts result
input.puts "a third string of input"
end
# and so forth
end