我在ruby脚本中运行一个长时间运行的shell命令,如下所示:
Open3.popen2(command) {|i,o,t|
while line = o.gets
MyRubyProgram.read line
puts line
end
}
所以我可以在shell窗口中查看命令输出。
如何将STDIN附加到命令输入?
答案 0 :(得分:1)
你需要:
popen3 -- o
您可能需要IO.select
或其他IO调度程序,或其他一些多任务调度程序,例如Thread
。
以下是Thread
方法的演示:
require 'open3'
Open3.popen3('ruby -e "while line = gets; print line; end"') do |i, o, t|
tin = Thread.new do
# here you can manipulate the standard input of the child process
i.puts "Hello"
i.puts "World"
i.close
end
tout = Thread.new do
# here you can fetch and process the standard output of the child process
while line = o.gets
print "COMMAND => #{line}"
end
end
tin.join # wait for the input thread
tout.join # wait for the output thread
end