【问题标题】:Capturing STDOUT and STDERR of an external program *while* it's executing (Ruby)捕获外部程序的 STDOUT 和 STDERR *while* 它正在执行(Ruby)
【发布时间】:2009-10-30 13:01:47
【问题描述】:

场景:

我必须从我的 Ruby 脚本中调用一个外部程序,这个程序会向 stdout 和 stderr 发送很多有用(但神秘)的信息。

程序运行时,我想解析它发送到 stdout 和 stderr 的行:

  • 如果没有必要,删除它们
  • 必要时重新格式化/替换它们

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

有什么想法吗?

哦,我在 Windows 上:-(

【问题讨论】:

  • 你能举一个你的“技巧”的例子吗(比如说,popen)?
  • 我猜 Windows 没有管道?
  • @jug: Windows 有完全有效的管道。

标签: windows ruby


【解决方案1】:

其实它比我想象的要简单,这似乎工作得很好:

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 上运行!

【讨论】:

    猜你喜欢
    • 2013-09-02
    • 1970-01-01
    • 2020-06-23
    • 2014-08-05
    • 2018-10-31
    • 1970-01-01
    • 1970-01-01
    • 2011-06-07
    • 2019-06-18
    相关资源
    最近更新 更多