From: Brian Marick Date: 2001-09-22T07:09:53+09:00 Subject: [ruby-talk:21502] Re: Interaction system() / $stdout ? At 02:39 PM 9/20/01, you wrote: >This appears to work: > >$saved_stdout = $stdout.dup >$stdout = File.open("log-file", "w") >system "echo After redirect, to log-file I hope." >$stdout = $saved_stdout.dup >system "echo Original restored, to STDOUT I hope." > >I'm not sure why that second "dup" is necessary, perhaps a guru can >elaborate or give a better solution. I think the solution needs to be more complicated. Try closing the logfile before restoring stdout: $saved_stdout = $stdout.dup $stdout = File.open("log-file", "w") system "echo After redirect, to log-file I hope." $stdout.close ###### New line $stdout = $saved_stdout.dup ### this is line 5 system "echo Original restored, to STDOUT I hope." The result of the system is this: test4.rb:5: closed stream (IOError) Note that the line number is the second assignment to stdout, not the attempt to write to it. It seems you have to stash the stream in a temp, reassign stdout, and then close stdout: $saved_stdout = $stdout.dup $stdout = File.open("log-file", "w") puts "echo After redirect, to log-file I hope." $saved_internal_stdout = $stdout ###### New line $stdout = $saved_stdout.dup $saved_internal_stdout.close ###### New line puts "echo Original restored, to STDOUT I hope." By the way, it doesn't seem to me that the second dup is needed. Seems to work without it. Why do you think it's needed? This is all complicated enough that I'm going to extend my Fluid variables package to handle it: Fluid.redirect(["$stdout", File.open("logfile", 'w')]) { puts "this goes to the logfile" } puts "this goes back to the old $stdout" But I'd like to know if the above sequence of steps really works, or just doesn't obviously fail. -- Brian Marick, marick@testing.com www.testing.com - Software testing services and resources www.testingcraft.com - Where software testers exchange techniques www.visibleworkings.com - Adequate understanding of system internals