Capturing stdout from cmd while letting it print it

Assuming you’re in a command-line context, what you want is the "tee"
command. It’s standard in unix, and available for Windows in either
cygwin (open source), or the MKS Toolkit (commercial). Pipe the output of
your script to tee, and it prints it to a file as well as passing through
to stdout. You run something like this:

$ myscript.rb | tee myscript.out

The output of myscript.rb appears on the screen, and goes to myscript.out
as well. Another useful trick when doing this is to redirect stderr to
stdout, then tee it:

$ myscript.rb 2>&1 | tee myscript.out

This may not be exactly the answer you’re looking for, but believe me,
learning unix-style shell programming is a LOT faster and more flexible
than doing it all in Ruby, or any other scripting language. The Unix
shell is a wondrous thing.

coma_killen@fastmail.fm
09/18/02 02:10 AM
Please respond to ruby-talk

···

To: ruby-talk@ruby-lang.org (ruby-talk ML)
cc:
Subject: Capturing stdout from cmd while letting it print it

Hi,

I want to capture the output from a program but still have it print to
STDOUT.
I tried

r = []
IO.popen(“mycmd”) do |pipe|
while (line = pipe.gets)
r << line
STDOUT.puts line
end
end

but the output will only come after the command has finished running.
This doesn’t
work here since the command runs for very long and the user will want
the output.

Is there a pure-Ruby way (that works on Windows!) for capturing the
output of
a command without “disturbing” its normal output to STDOUT?

Sorry if this is very basic but I have a windows background… :wink:

Regards,

Karsten