12

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?

2 Answers 2

20

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
Sign up to request clarification or add additional context in comments.

1 Comment

The output is actually buffered until the command is completed then you will see the output, if you don't care the real-timeliness.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.