2

Whenever I wish to run some outside process in Ruby I write something like this:

output = `outer_process`

This works well, and the output of the process is placed into "output". But sometimes the process takes a lot of time and gives a lot of output and I would like to see it on the screen even before it stopped running. Is there a way to do this?

Gadi A
  • 3,449
  • 8
  • 36
  • 54

1 Answers1

1

Take a look at the open4 gem. There are some limitations, but assuming there is output to STDOUT from your process, you could do something like this:

Open4.open4( outer_process ) do | pid, pstdin, pstdout, pstderr |
  pstdout.each { |line| puts line }
end

This is pretty similar, in terms of underlying mechanisms, to Anand's suggestion in comments.

Note this will not work immediately if the process you call is not flushing STDOUT. If you need to work around that limitation, you will need to provide a terminal for the child process, which is possible in Ruby, but more complicated - see answer to Continuously read from STDOUT of external process in Ruby

Community
  • 1
  • 1
Neil Slater
  • 26,512
  • 6
  • 76
  • 94
  • 2
    I found this post that describes a solution for the issue where processes do not flush to STDOUT: http://stackoverflow.com/questions/1154846/continuously-read-from-stdout-of-external-process-in-ruby – mario Jul 09 '13 at 12:28
  • @mario: Nice find. Solution is complex though, so I will just add to answer as a link. – Neil Slater Jul 09 '13 at 12:32