From: Damphyr Date: 2006-05-17T20:58:51+09:00 Subject: Re: Capturing stdout Robert Klemme 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? > > You can use popen but then your code is in another process. > >> (Now that I think of it would StringIO do for stdout redirection?) > > Yes, but you then must explicitely use a receiver with those puts > statements as Kernel.puts still sends to $DEFOUT. Yes, but I can change Kernel#puts :) These files are tests, written using a simple DSL and then run just like rake runs it's rakefiles. So I am loath to require receivers for puts or any other logging facility (I am the only one in my project comfortable with Ruby, although everyone agrees that it saves them a lot of time and trouble). popen was my obvious choice (it's already in use in this whole mess) but I was wondering if there was another way. Oh, well. Cheers, V.- -- http://www.braveworld.net/riva ____________________________________________________________________ http://www.freemail.gr - ������ �������� ������������ ������������. http://www.freemail.gr - free email service for the Greek-speaking.