From: Mark Volkmann Date: 2006-05-17T21:26:09+09:00 Subject: Re: Capturing stdout Here's another alternative. # Create a string object to receive the output. dest = '' # Add a write method to this string object. def dest.write(data); self << data; end old_stdout, $stdout = $stdout, dest # Invoke code that uses puts. # Restore stdout. $stdout = old_stdout On 5/17/06, Daniel Harple wrote: > 2006/5/17, Damphyr : > > I have code that prints to stdout (using puts and/or print). > > I'm loading the code from a file (pretty much the way rake handles > > rakefiles) and would like to capture the output from the loaded code. > > I don't want to redirect stdout into a file or anywhere else, I > > need the > > output in a string. > > > > ---file1.rb > > puts "Output of meaningful code omitted" > > ---loader.rb > > > > begin > > ###do some magic to get the stdout from this point on into a string > > load file1.rb > > ###do some more magic to put stdout back where it was. > > end > > > > Has anyone a solution for this? > > require 'stringio' > stdout = StringIO.new > $stdout = stdout > load "file1.rb" > $stdout = STDOUT > stdout.rewind > puts "got: #{stdout.read}" # => got: Output of meaningful code omitted > > -- Daniel > > > > -- R. Mark Volkmann Object Computing, Inc.