Ruby怎么实现在从外部过程的STDOUT中不断读取?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (10)

我想通过一个ruby脚本从命令行运行blender,然后处理由blender逐行提供的输出,以更新GUI中的进度条。blender是我需要阅读的外部流程,这并不是很重要。

当blender进程仍在运行时,我似乎无法捕捉到进度消息,blender通常print到shell,而且我尝试了几种方法。都不行

下面是一个失败尝试的例子。它确实获得并打印了blender输出的前25行,但只能在blender过程退出之后:

blender = nil
t = Thread.new do
  blender = open "| blender -b mball.blend -o //renders/ -F JPEG -x 1 -f 1"
end
puts "Blender is doing its job now..."
25.times { puts blender.gets}

提问于
用户回答回答于

以下是简短的答案:

以下列方式使用PTY.spawch

require 'pty'
cmd = "blender -b mball.blend -o //renders/ -F JPEG -x 1 -f 1" 
begin
  PTY.spawn( cmd ) do |stdout, stdin, pid|
    begin
      # Do stuff with the output here. Just printing to show it works
      stdout.each { |line| print line }
    rescue Errno::EIO
      puts "Errno:EIO error, but this probably just means " +
            "that the process has finished giving output"
    end
  end
rescue PTY::ChildExited
  puts "The child process exited!"
end

用户回答回答于

使用IO.popen是个很好的例子。

代码如下:

blender = nil
t = Thread.new do
  IO.popen("blender -b mball.blend -o //renders/ -F JPEG -x 1 -f 1") do |blender|
    blender.each do |line|
      puts line
    end
  end
end

扫码关注云+社区