【问题标题】:Suppress STDOUT from a Ruby C extension从 Ruby C 扩展中抑制 STDOUT
【发布时间】:2012-05-17 22:41:00
【问题描述】:

我在 project 中使用 gem dep_selector,但不知道如何从库的 C 扩展中抑制标准输出。

我想压制的有问题的代码在这里:

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

有什么想法吗?

【问题讨论】:

    标签: ruby stdout stderr


    【解决方案1】:

    您也许可以从 Rails 中刷一些代码,例如 quietly 方法,它应该会为您解决这个问题。

    Kernel#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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-26
      • 2012-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-07
      相关资源
      最近更新 更多