问题
I'm using the gem dep_selector in a project and can't figure out how to suppress the stdout from the library's C extensions.
The code in question I want to suppress is here:
https://github.com/RiotGames/knife_cookbook_dependencies/blob/master/lib/kcd/shelf.rb#L26
I tried this:
real_stdout = $stdout
$stdout = StringIO.new
real_stderr = $stderr
$stderr = StringIO.new
puts "This gets suppressed correctly"
selector.find_solution( ... ) # still prints to the terminal
but I still get dep_selector output when I run the script.
Any ideas?
回答1:
You might be able to swipe some code from Rails, like the quietly method, that should take care of this for you.
Kernel#quietly uses the following to silence STDOUT and STDERR
# Silences any stream for the duration of the block.
#
# silence_stream(STDOUT) do
# puts 'This will never be seen'
# end
#
# puts 'But this will'
def silence_stream(stream)
old_stream = stream.dup
stream.reopen(RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ ? 'NUL:' : '/dev/null')
stream.sync = true
yield
ensure
stream.reopen(old_stream)
end
来源:https://stackoverflow.com/questions/10644457/suppress-stdout-from-a-ruby-c-extension