从 Ruby C 扩展中抑制 STDOUT [英] Suppress STDOUT from a Ruby C extension

查看:23
本文介绍了从 Ruby C 扩展中抑制 STDOUT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 project 并且无法弄清楚如何从库的 C 扩展中抑制标准输出.

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

我试过了:

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 输出.

but I still get dep_selector output when I run the script.

有什么想法吗?

推荐答案

您可以从 Rails 中刷取一些代码,例如 安静 方法,它应该为您解决这个问题.

You might be able to swipe some code from Rails, like the quietly method, that should take care of this for you.

Kernel#quietly 使用以下代码来静音 STDOUT 和 STDERR

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

这篇关于从 Ruby C 扩展中抑制 STDOUT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆