Suppress STDOUT from a Ruby C extension

本秂侑毒 提交于 2019-12-23 04:38:28

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!