Skip to content

Instantly share code, notes, and snippets.

@mirakui
Created November 7, 2012 02:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mirakui/4029268 to your computer and use it in GitHub Desktop.
Save mirakui/4029268 to your computer and use it in GitHub Desktop.
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