A convoluted question about stdout

S

Sonny Chee

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.
 
B

Brian Candler

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.
 
S

Sean O'Halpin

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.
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
 
S

Sonny Chee

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,239
Messages
2,571,200
Members
47,840
Latest member
Tiffany471

Latest Threads

Top