19
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rubyで外部コマンド実行結果を一行づつ受け取る

Posted at

こういう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

Ruby 2.1.0 リファレンスマニュアル | class IO

19
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?