Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I have console output display to stdout AND store it in a variable?

If I do this:

output = %x{some_script}

...then I have the stuff printed to stdout stored in output; but I don't see it appear on the screen.

On the other hand, if I do this:

success = system "some_script"

...then I see the output appear on the screen, but I don't have it stored in a variable (success just holds a boolean value).

Is there some way to get both? I'm aware I could do this:

output = %x{some_script}
puts output

But the problem there is that some_script might be a pretty long-running script, in which case I see nothing until the whole thing is finished. I'd prefer to see output as it's produced, and when it's finished to have it all stored in the output variable.

like image 300
Dan Tao Avatar asked Sep 01 '11 20:09

Dan Tao


People also ask

How do you store console output in variables?

If you want to do this to an object that has been already logged (one time thing), chrome console offers a good solution. Hover over the printed object in the console, right click, then click on "Store as Global Variable". Chrome will assign it to a temporary var name for you which you can use in the console.

Is stdout same as console?

By default, most systems have their standard output set to the console, where text messages are shown, although this can generally be redirected. I've never heard of a system where stdout is anything other than a console window, by default or otherwise.


2 Answers

This is a solution with 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
like image 79
Hector Castro Avatar answered Nov 03 '22 00:11

Hector Castro


You could monkeypatch Kernel::puts, but I can only think of a kludgy global way to store the results:

class Kernel
  alias_method :old_puts, :puts
  def puts(*args)
    old_puts args
    $output << args
  end
end
like image 27
wersimmon Avatar answered Nov 03 '22 02:11

wersimmon