From: Brian Candler Date: 2009-05-20T19:29:54+09:00 Subject: Re: I want to redirect stderr to StringIO. ErMaker wrote: >>> IO.new(2).reopen(StringIO.new) > TypeError: can't convert StringIO into String > from (irb):1:in `reopen' > from (irb):1 >>> IO.new(2).reopen(IO.new(1)) > => # > > StringIO also do as IO, but IO#reopen fails. > > I want to redirect stderr to StringIO, but it doesn't work. The problem is that a StringIO cannot exist in the O/S's file descriptor table. STDERR.reopen(...) at the low level does a dup() or dup2() to copy one file descriptor to another. You have two options: (1) $stderr = StringIO.new Then any program which writes to $stderr will be fine. But anything which writes to STDERR will still go to file descriptor 2 (that is, your process' stderr file) (2) reopen STDERR with something which exists in the O/S file descriptor table: e.g. a file or a pipe. So for example, you can fork and connect a pipe to the child process' STDERR, and then in the parent have a thread which reads from this and copies all data read into a StringIO object. Anything written to STDERR in the child process will be collected into the StringIO via the pipe. See open3.rb in the standard library for an example of how to do this. -- Posted via http://www.ruby-forum.com/.