こういうRubyのコードがあって
target.rb
10.times do |i|
sleep 0.1
puts i
end
別のRubyのプログラムから上記スクリプトを実行して、結果を一行づつ取得したい。Ruby弱なので1時間くらい調べた。。
IO.popen
を使う。
script.rb
IO.popen('ruby target.rb').each do |line|
puts line.chomp
end
ただしこのままだと対象のRubyスクリプトが出力をバッファリンスするので、target.rb
の実行が終わるまで結果が渡ってこない。
target.rb
に以下の行を足すとバッファリングしないようにできる。
target.rb
STDOUT.sync = true
標準エラーも取得したいときはIO.popen
のオプションで標準エラーをリダイレクトするように指定する。
target.rb
STDOUT.sync = true
10.times do |i|
sleep 0.1
puts "stdout: #{i}"
warn "stderr: #{i}"
end
script.rb
IO.popen('ruby target.rb', :err => [:child, :out]).each do |line|
puts line.chomp
end