Skip to content

Instantly share code, notes, and snippets.

@alabamaair
Forked from moertel/suppress_ruby_output.rb
Created November 29, 2017 10:20
Show Gist options
  • Save alabamaair/9b2c237edf301583546ff8853f2d6a55 to your computer and use it in GitHub Desktop.
Save alabamaair/9b2c237edf301583546ff8853f2d6a55 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