Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

windows

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:

  • 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 retrieve stdout/stderr after the program is executed, not during its execution.

Any ideas?

Oh, and I'm on Windows :-(

like image 559
h3rald Avatar asked Oct 30 '09 13:10

h3rald


1 Answers

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!

like image 55
h3rald Avatar answered Oct 21 '22 05:10

h3rald