Star
You must be signed in to star a gist
Temporarily suppress STDOUT and STDERR (ruby)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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