Skip to content

Instantly share code, notes, and snippets.

@mirakui mirakui/capture.rb
Created Nov 7, 2012

Embed
What would you like to do?
capturing stdout and stderr
def capture(options={})
out = options[:out]
err = options[:err] || :out
stdout_old = $stdout.dup
stderr_old = $stderr.dup
$stdout.reopen out
err = $stdout if err == :out
$stderr.reopen err
yield
ensure
$stdout.flush
$stderr.flush
$stdout.reopen stdout_old
$stderr.reopen stderr_old
end
if __FILE__ == $0
capture(:out => open('a.txt', 'w')) do
STDOUT.puts 'STDOUT.puts'
system 'echo "system"'
STDERR.puts 'STDERR.puts'
end
end
__END__
$ cat a.txt
STDOUT.puts
system
STDERR.puts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.