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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With