Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Ruby access output from shell commands as it appears?

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?

like image 383
Ciryon Avatar asked Apr 29 '10 22:04

Ciryon


1 Answers

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

pipe = IO.popen("netstat 3")
while (line = pipe.gets)
  print line
  print "and"
end
like image 133
Marcel Jackwerth Avatar answered Oct 17 '22 09:10

Marcel Jackwerth