How can I display console output in stdout and store it in a variable?

If I do this:

output = %x{some_script}

... then I have stuff printed in stdout, stored in output; but I do not see it on the screen.

On the other hand, if I do this:

success = system "some_script"

... then I see that the output appears on the screen, but I did not store it in a variable (it successjust contains a boolean).

Is there a way to get both? I know I can do this:

output = %x{some_script}
puts output

But the problem is that it some_scriptcan be a rather long script, in which case I don’t see anything until it all ends. I would rather see the output as it is created, and when it is finished, so that all this is stored in a variable output.

+5
2

IO.popen:

require 'stringio'

output = StringIO.new

IO.popen("ls") do |pipe|
  pipe.each do |line|
    output.puts line
    puts line
  end
end

puts output.string # => Outputs the contents of `output` as a string
+7

monkeypatch Kernel::puts, :

class Kernel
  alias_method :old_puts, :puts
  def puts(*args)
    old_puts args
    $output << args
  end
end
+1

All Articles