Last active
March 21, 2024 08:54
-
-
Save moertel/11091573 to your computer and use it in GitHub Desktop.
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 | |
original_stderr = $stderr.clone | |
original_stdout = $stdout.clone | |
$stderr.reopen(File.new('/dev/null', 'w')) | |
$stdout.reopen(File.new('/dev/null', 'w')) | |
yield | |
ensure | |
$stdout.reopen(original_stdout) | |
$stderr.reopen(original_stderr) | |
end |
π @iamtheiconoclast
π π
Nice one guys! Very useful :)
Awesome little ditty.
How can this be edited to instead of just suppressing by sending to dev/null, it instead returned the output so that it can be stored in a variable? Can this be done without redirecting to a file?
@nancy-gomez, for this you might want to use https://docs.ruby-lang.org/en/2.5.0/Open3.html#method-c-popen3
@iamtheiconoclast I realise I never looked at the comments here. π Thanks for your suggested simplifications; I've amended the Gist to reflect them.
Windows Version with File::NULL
# 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
original_stderr = $stderr.clone
original_stdout = $stdout.clone
$stderr.reopen(File.new(File::NULL, 'w'))
$stdout.reopen(File.new(File::NULL, 'w'))
yield
ensure
$stdout.reopen(original_stdout)
$stderr.reopen(original_stderr)
end
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fantastic! Thank you, this is exactly what I was looking for. (I also used it to stop output from an inline Sinatra app :)
I believe it can be simplified quite a bit:
begin
/end
is unnecessary since therescue
andensure
clauses can be hooked onto the method itself (I love Ruby!)rescue
clause is unnecessary since theensure
clause will run anyway before the exception is passed on up the call stack, meaning output will be turned back on before the exception has a chance to get caught (or not) by the calling coderetval
is unnecessary since the return value of the method will be the result of yielding to the block anywayretval =
is also unnecessaryPutting that all together, it now looks like this: