如何将控制台输出显示到stdout并将其存储在变量中?

时间:2023-02-12 20:46:52

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.

...然后我将打印到stdout的东西存储在输出中;但我没有看到它出现在屏幕上。

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.

但问题是some_script可能是一个非常长时间运行的脚本,在这种情况下,在整个事情完成之前我什么都看不见。我更愿意看到它产生的输出,以及它完成时将它全部存储在输出变量中。

2 个解决方案

#1


8  

This is a solution with IO.popen:

这是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

#2


1  

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

你可以monkeypatch Kernel :: puts,但我只能想到一种存储结果的kludgy全局方式:

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

#1


8  

This is a solution with IO.popen:

这是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

#2


1  

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

你可以monkeypatch Kernel :: puts,但我只能想到一种存储结果的kludgy全局方式:

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