[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

A convoluted question about stdout

Sonny Chee

4/6/2007 6:29:00 AM

Hey Guys,

I know I can do a $stdout.reopen and redirect it to a file. Is there a
more direct way to get at the contents of stdout... say, redirect stdout
to variable?

Sonny.

--
Posted via http://www.ruby-....

4 Answers

Brian Candler

4/6/2007 7:22:00 AM

0

On Fri, Apr 06, 2007 at 03:29:12PM +0900, Sonny Chee wrote:
> I know I can do a $stdout.reopen and redirect it to a file.

Note that STDOUT is tied to the underlying operating system's concept of
"standard output" - for Unix this is the open file on file descriptor 1. So
if you *reopen* $stdout (or STDOUT) you'll change what fd 1 points at. Then,
anything else which writes directly to fd 1 - e.g. C extensions, or external
programs run using system() or exec() - will also write to this file.

Now, you can change the global variable $stdout to point to a different IO
object. In that case, anything in Ruby which does "$stdout.puts" will write
to that new object. But anything which writes directly to fd 1 will still be
writing to whatever the OS has attached to fd 1.

Regards,

Brian.

Sean O'Halpin

4/6/2007 2:28:00 PM

0

On 4/6/07, Sonny Chee <sonny.chee@gmail.com> wrote:
> Hey Guys,
>
> I know I can do a $stdout.reopen and redirect it to a file. Is there a
> more direct way to get at the contents of stdout... say, redirect stdout
> to variable?
>
> Sonny.
>
> --
> Posted via http://www.ruby-....
>
>
Maybe something like this (a variation on Bruce's post):

def capture_stdout(&block)
raise ArgumentError, "No block given" if !block_given?
old_stdout = $stdout
$stdout = sio = StringIO.new
yield
$stdout = old_stdout
sio.rewind
sio.read
end

txt = capture_stdout do
puts "dlroW olleH"
end
puts txt.reverse

Regards,
Sean

Sonny Chee

4/6/2007 5:07:00 PM

0

Interesting, that's good info. Thanks Brian.

Sonny.

--
Posted via http://www.ruby-....

Sonny Chee

4/6/2007 5:10:00 PM

0

Thanks Sean. This is exactly what I was looking for.... for some reason
I overlooked the StringIO class when I was perusing the Standard Library
listing.

Sonny.


Sean O'halpin wrote:
> On 4/6/07, Sonny Chee <sonny.chee@gmail.com> wrote:
>>
>>
> Maybe something like this (a variation on Bruce's post):
>
> def capture_stdout(&block)
> raise ArgumentError, "No block given" if !block_given?
> old_stdout = $stdout
> $stdout = sio = StringIO.new
> yield
> $stdout = old_stdout
> sio.rewind
> sio.read
> end
>
> txt = capture_stdout do
> puts "dlroW olleH"
> end
> puts txt.reverse
>
> Regards,
> Sean


--
Posted via http://www.ruby-....