Running a shell command from Ruby: capturing the output while displaying the output?

后端 未结 7 1450

I have a problem.

I want to run a ruby script from another ruby script and capture it\'s output information while letting it output to the screen too.

runner

7条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-10 02:54

    Try this:

    rd, wr = IO::pipe
    pid = Process.fork do  
      $stdout.reopen(wr)
      rd.close
      exec("command")
    end
    wr.close
    rd.each do |line|  
      puts "line from command: #{line}"
    end
    Process.wait(pid)
    

    Similar if you want to capture stderr. If you need to capture both it would a bit more difficult (Kernel.select?)

    Edit: Some explanation. This is an ancient Unix procedure: pipe + fork + calls to dup2 (reopen) depending on what you want. In a nutshell: you create a pipe as a means of communication between child and parent. After the fork, each peer close the pipe's endpoint it does not use, the child remaps (reopen) the channel you need to the write endpoint of the pipe and finally the parent reads on the read channel of the pipe.

提交回复
热议问题