从Ruby C扩展中抑制STDOUT

我在项目中使用gem dep_selector ,无法弄清楚如何从库的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输出。

有任何想法吗?

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

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