Skip to content

Instantly share code, notes, and snippets.

@moertel
Last active March 21, 2024 08:54
Show Gist options
  • Star 34 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save moertel/11091573 to your computer and use it in GitHub Desktop.
Save moertel/11091573 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
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
@nav-mike
Copy link

👍 🎉

@robsimpsondev
Copy link

Nice one guys! Very useful :)

@gangelo
Copy link

gangelo commented Jan 31, 2019

Awesome little ditty.

@nancy-gomez
Copy link

nancy-gomez commented May 28, 2019

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?

@EricDuminil
Copy link

@moertel
Copy link
Author

moertel commented Aug 30, 2019

@iamtheiconoclast I realise I never looked at the comments here. 😅 Thanks for your suggested simplifications; I've amended the Gist to reflect them.

@Largo
Copy link

Largo commented Sep 27, 2022

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