From: Richard Ryan Date: 2002-08-19T14:45:05+09:00 Subject: Re: How do I dup file descriptors in ruby? (diverting STDERR) ts writes: > >>>>> "R" == Richard Ryan writes: > > R> Yes, those are right along the lines I was thinking, and that actually > R> was the first thing I tried but, and maybe I'm being too picky, if I > R> put that through irb and check $stderr.fileno I get something other > R> than 2. That really kind of bugs me for some reason. It just don't > R> seem right. > > This is because you must use $stderr.reopen, something like this > > pigeon% cat b.rb > #!/usr/bin/ruby > def redirect(*args) > defout = $defout > stdout = $stdout.clone > stderr = $stderr.clone > $defout = File.new *args > $defout.sync = true > $stdout.reopen($defout) > $stderr.reopen($defout) > yield > ensure > $defout.close > $stdout.reopen(stdout) > $stderr.reopen(stderr) > $defout = defout > end > > redirect('aaa', 'w') do > puts "hello world" > puts $stdout.fileno > puts $stderr.fileno > system("ls -l nonexistent_file") > system("ls /etc/passwd") > end > puts "Hello World" > puts $stdout.fileno > puts $stderr.fileno > system("ls -l nonexistent_file") > system("ls /etc/group") > pigeon% > > pigeon% b.rb > Hello World > 1 > 2 > ls: nonexistent_file: No such file or directory > /etc/group > pigeon% > > pigeon% cat aaa > hello world > 1 > 2 > ls: nonexistent_file: No such file or directory > /etc/passwd > pigeon% > > Guy Decoux Hi all, I guess I have to take back what I said about complexity. Although this is laid out similarly to the code that was here before, there's something about how this brings all the other answers together that shows me where my perceptions were perhaps a tad warped by naivete. It takes awhile to adjust when you're used to seeing things a certain way---I used Korn as an example just because that's where I've seen this most commonly done and how I've most commonly used it myself. Thanks to everyone who answered. This article here somehow demonstrates to me what was going on with the other articles. Maybe if there's a ruby cookbook somewhere, maybe this would be good to have in there. Does anyone else agree? FAQ maybe? Thanks again, Richard Ryan