Ciryon
Ciryon

Reputation: 2777

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?

Upvotes: 12

Views: 3947

Answers (2)

Marcel Jackwerth
Marcel Jackwerth

Reputation: 54752

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

Upvotes: 20

Francisco Soto
Francisco Soto

Reputation: 10392

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.

Upvotes: 0

Related Questions