捕获一个外部程序在执行期间的标准输出和标准错误流(Ruby)

9

场景:

我需要从我的Ruby脚本中调用一个外部程序,该程序将大量有用(但晦涩难懂)的信息发送到标准输出和标准错误。

当程序正在运行时,我想解析它发送到标准输出和标准错误的行,并且:

  • 如果不必要,则删除它们
  • 如果必要,则重新格式化/替换它们

我尝试了所有常规技巧(system、exec、popen、popen3、反引号等等),但我只能在程序执行后检索stdout/stderr,而不能在其执行期间进行检索。

有什么想法吗?

哦,我在Windows上:-(


你能举一个你的“技巧”的例子吗?(比如popen) - Kathy Van Stone
我猜Windows没有管道? - j.p.
@jug:Windows拥有完全有效的管道。 - Adrien Plisson
1个回答

14

实际上,这比我想象的要简单,这似乎完美地运行:

STDOUT.sync = true # That's all it takes...
IO.popen(command+" 2>&1") do |pipe| # Redirection is performed using operators
  pipe.sync = true
  while str = pipe.gets
    puts "-> "+str # This is synchronous!
  end
end

...而且,它在Windows上也可以工作!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接