How to wait for process to finish using IO.popen?

后端 未结 6 1587
北海茫月
北海茫月 2020-12-29 06:14

I\'m using IO.popen in Ruby to run a series of command line commands in a loop. I then need to run another command outside of the loop. The command outside of t

6条回答
  •  孤城傲影
    2020-12-29 06:37

    Use the block form and read all the content:

    IO.popen "cmd" do |io|
      # 1 array
      io.readlines
    
      # alternative, 1 big String
      io.read
    
      # or, if you have to do something with the output
      io.each do |line|
        puts line
      end
    
      # if you just want to ignore the output, I'd do
      io.each {||}
    end
    

    If you do not read the output, it may be that the process blocks because the pipe connecting the other process and your process is full and nobody reads from it.

提交回复
热议问题