Capturing STDOUT and STDERR of an external program * while * it executes (Ruby)

Scenario:

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

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

  • Remove them if not necessary.
  • Reformat / replace them if necessary

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

Any ideas?

Oh, and I'm on Windows: - (

+8
windows ruby
Oct 30 '09 at 13:01
source share
1 answer

Actually, it was easier than I thought, it looks great:

STDOUT.sync = true # That 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!

+14
Nov 03 '09 at 9:03
source share



All Articles