Reading the output of a program "in real-time"

Hi Rubists :wink:

I’m still learning Ruby, and I have a small question.

Is there a way to read the output of a program “line by line”, in
real-time ?

I would like to execute CVSup and to display its output in a Gtk
list-view component each time CVSup prints a line on $stdout.

I have experimented 3 tests: each one prints directly the output in one
shot (this is not what I want) :

···

TEST 1

IO.popen("./plok") { |pipe|
pipe.each_line { |line|
puts line
}
}

TEST 2

rd, wr = IO.pipe

fork {
puts “child”
$stdout = wr
rd.close
exec("./plok")
}

wr.close
puts "father = waiting for output"
while rd.gets do
puts "==> #{$_}"
end

TEST 3

IO.popen("./plok") { |ruby|
while ruby.gets do
puts("==> #{$_}")
end
}


Thank you in advance (and excuse-me for my bad english),


Laurent

Hi,

Is there a way to read the output of a program “line by line”, in
real-time ?

You have to let the program recognize stdout as a tty.

require ‘pty’
PTY.spawn(“./plok”) do |r, w|
r.each do |line|
puts(“==> #{l}”)
end
end

···

At Fri, 28 Feb 2003 19:38:43 +0900, Laurent Sansonetti wrote:


Nobu Nakada

Thank you very much !

I have updated the code a little bit, because r.each() seems to throw a
RuntimeError exception (“Child_changed: X”) when the process dies.

require ‘pty’
PTY.spawn(“./plok”) do |r, w|
begin
r.each do |line|
puts(“==> #{line}”)
end
rescue RuntimeError => err
raise unless err.message =~ /Child_changed/
end
end

···

nobu.nokada@softhome.net wrote:

require ‘pty’
PTY.spawn(“./plok”) do |r, w|
r.each do |line|
puts(“==> #{l}”)
end
end


Laurent