Skip to content

Instantly share code, notes, and snippets.

@awesome
Forked from moertel/suppress_ruby_output.rb
Created January 21, 2017 10:09
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save awesome/f2504898b05302c56ecc367595920880 to your computer and use it in GitHub Desktop.
Temporarily suppress STDOUT and STDERR (ruby)
# Temporarily redirects STDOUT and STDERR to /dev/null
# but does print exceptions should there occur any.
# Call as:
# suppress_output { puts 'never printed' }
#
def suppress_output
begin
original_stderr = $stderr.clone
original_stdout = $stdout.clone
$stderr.reopen(File.new('/dev/null', 'w'))
$stdout.reopen(File.new('/dev/null', 'w'))
retval = yield
rescue Exception => e
$stdout.reopen(original_stdout)
$stderr.reopen(original_stderr)
raise e
ensure
$stdout.reopen(original_stdout)
$stderr.reopen(original_stderr)
end
retval
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment