Reputation: 85
I'm using IO.popen
to start a subprocess, but I only get the result of everything that happened in the time it took for the subprocess to run (sometimes 5 minutes or whatever) when the subprocess exits. I really need to be able to see everything the subprocess writes to stderr
and stdout
as-and-when it happens.
So far I could not find anything that works like this, but I'm sure it's possible.
Upvotes: 7
Views: 1459
Reputation: 12225
You might want to use Open3.popen3 from standard library, it gives access to stdin, stdout, and stderr as streams.
Upvotes: 0
Reputation:
if you need to get output in real time i would recommend to use stdlib PTY
instead of popen
something like this:
require 'pty'
cmd = 'echo a; sleep 1; cat /some/file; sleep 1; echo b'
PTY.spawn cmd do |r, w, pid|
begin
r.sync
r.each_line { |l| puts "#{Time.now.strftime('%M:%S')} - #{l.strip}" }
rescue Errno::EIO => e
# simply ignoring this
ensure
::Process.wait pid
end
end
exit "#{cmd} failed" unless $? && $?.exitstatus == 0
> 33:36 - a
> 33:37 - cat: /some/file: No such file or directory
> 33:38 - b
this way you get output instantly, just as in terminal
Upvotes: 7