How do I temporarily redirect stderr in Ruby?

后端 未结 4 1365
暗喜
暗喜 2020-11-28 07:34

I\'d like to temporarily redirect stderr in a Ruby script for the duration of a block, ensuring that I reset it to its original value at the end of the block.

I had

4条回答
  •  执笔经年
    2020-11-28 08:06

    I like the StringIO answers. But if you are calling an external process, and $stderr = StringIO.new doesn't work, you might write stderr out to a temporary file:

    require 'tempfile'
    
    def capture_stderr
      backup_stderr = STDERR.dup
      begin
        Tempfile.open("captured_stderr") do |f|
          STDERR.reopen(f)
          yield
          f.rewind
          f.read
        end
      ensure
        STDERR.reopen backup_stderr
      end
    end
    

提交回复
热议问题