Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream output of child process in Ruby

Tags:

ruby

I want to be able to stream the output of a child process in Ruby

e.g.

p `ping google.com`

I want to see the ping responses immediately; I don't want to wait for the process to complete.

like image 252
Sam Avatar asked Jan 04 '12 18:01

Sam


3 Answers

You can do the following instead of using backticks:

IO.popen('ping google.com') do |io|
  io.each { |s| print s }
end

Cheers!

like image 133
coreyward Avatar answered Nov 20 '22 21:11

coreyward


You should use IO#popen:

IO.popen("ping -c 3 google.com") do |data|
  while line = data.gets
    puts line
  end
end
like image 45
Dylan Markow Avatar answered Nov 20 '22 22:11

Dylan Markow


If you'd like to capture both the stdout and stderr you can use popen2e:

require 'open3'

Open3.popen2e('do something') do |_stdin, stdout_err, _wait_thr|
  stdout_err.each { |line| puts line }
end
like image 4
Bozhidar Batsov Avatar answered Nov 20 '22 21:11

Bozhidar Batsov