从Ruby C扩展中抑制STDOUT

时间:2012-05-17 22:41:01

标签: ruby stdout stderr

我在dep_selector中使用了gem project,并且无法弄清楚如何从库的C扩展中抑制stdout。

我想要压制的代码在这里:

https://github.com/RiotGames/knife_cookbook_dependencies/blob/master/lib/kcd/shelf.rb#L26

我试过了:

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

但是当我运行脚本时,我仍然得到dep_selector输出。

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

你可以从Rails中刷一些代码,比如quietly方法,它应该为你解决这个问题。

内核#安静地使用以下内容来静音STDOUT和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