views:

155

answers:

2

My Ruby script is running a shell command and parsing the output from it. However, it seems the command is first executed and output saved in an array. I would like to be able to access the output lines in real time just as they are printed. I've played around with threads, but haven't got it to work. Any suggestions?

+4  A: 

You are looking for pipes. Here is an example:

# This example runs the netstat command via a pipe
# and processes the data in Ruby as it come back

fhi = IO.popen("netstat 3")
while (line = fhi.gets)
  print line
  print "and"
end
Marcel J.
Excellent answer, thanks a lot!
Ciryon
A: 

When call methods/functions to run system/shell commands, your interpreter spawns another process to run it and waits for it to finish, then gives you the output.

Even if you use threads, the only thing that you would accomplish is not letting your program to hang while the command is run, but you still won't get the output till its done.

I think you can accomplish that with pipes, but I am not sure how.

@Marcel got it.

Francisco Soto