On Tue, 10 Feb 2004, Simon Strandgaard wrote:

> Date: Tue, 10 Feb 2004 12:14:39 +0100
> From: Simon Strandgaard <neoneye / adslhome.dk>
> Newsgroups: comp.lang.ruby
> Subject: capture stderr
> 
> I want to temporarily capture stderr output.  Im on a freebsd box, so pipe
> should work.

a pipe should work - but it's pretty tricky...

> What am I doing wrong?

* IO#read blocks until eof is read - your loop will only happen once and tries
  to read all data at once.  if you really wanted to do something like that
  you'd need to do something like

    require 'io/nonblock' # i love this module

    buf = ''
    loop do
      select [r], nil, nil
      buf << r.nonblock{ r.read } 
    end

  your 'read' blocks:

    ~/eg/ruby > cat a.rb
    r, w = IO.pipe
    t = Thread.new do
      puts 'selecting...'
      select [r], nil, nil
      p r.read
    end
    w.puts 42
    t.join
    puts 'never reached'

    ~/eg/ruby > ruby a.rb
    selecting...
    (hangs forever)   


in the end, i think you can accomplish this much more easily and portably:

  ~/eg/ruby > cat x.rb
  require 'test/unit'
  require 'stringio'

  class TestCapture < Test::Unit::TestCase
    def capture_stderr
      begin
        $stderr = StringIO.new
        yield
        $stderr.rewind && $stderr.read
      ensure
        $stderr = STDERR
      end
    end
    def test_capture_stderr
      str = capture_stderr { $stderr.puts("hello world") }
      assert_equal("hello world\n", str)
      $stderr.puts 'and $stderr still works...'
    end
  end

  ~/eg/ruby > ruby x.rb
  Loaded suite x
  Started
  and $stderr still works...
  .
  Finished in 0.000745 seconds.

  1 tests, 1 assertions, 0 failures, 0 errors


-a
-- 

ATTN: please update your address books with address below!

===============================================================================
| EMAIL   :: Ara [dot] T [dot] Howard [at] noaa [dot] gov
| PHONE   :: 303.497.6469
| ADDRESS :: E/GC2 325 Broadway, Boulder, CO 80305-3328
| STP     :: http://www.ngdc.noaa.gov/stp/
| NGDC    :: http://www.ngdc.noaa.gov/
| NESDIS  :: http://www.nesdis.noaa.gov/
| NOAA    :: http://www.noaa.gov/
| US DOC  :: http://www.commerce.gov/
|
| The difference between art and science is that science is what we
| understand well enough to explain to a computer.  
| Art is everything else.  
|   -- Donald Knuth, "Discover"
|
| /bin/sh -c 'for l in ruby perl;do $l -e "print \"\x3a\x2d\x29\x0a\"";done' 
===============================================================================