h3rald
h3rald

Reputation: 923

Capturing STDOUT and STDERR of an external program *while* it's executing (Ruby)

Scenario:

I have to call an external program from my Ruby script, and this program sends a lot of useful (but cryptic) info to stdout and stderr.

While the program is running, I'd like to parse the lines it sends to stdout and stderr and:

I tried all the usual tricks (system, exec, popen, popen3, backticks, etc. etc.), but I can only retrieve stdout/stderr after the program is executed, not during its execution.

Any ideas?

Oh, and I'm on Windows :-(

Upvotes: 9

Views: 2106

Answers (1)

h3rald
h3rald

Reputation: 923

Actually, it was simpler than I thought, this seems to work perfectly:

STDOUT.sync = true # That's all it takes...
IO.popen(command+" 2>&1") do |pipe| # Redirection is performed using operators
  pipe.sync = true
  while str = pipe.gets
    puts "-> "+str # This is synchronous!
  end
end

...and yes, it works on Windows!

Upvotes: 14

Related Questions