I want to be able to stream the output of a child process in Ruby
e.g.
p `ping google.com`
I want to see the ping responses immediately; I don't want to wait for the process to complete.
You can do the following instead of using backticks:
IO.popen('ping google.com') do |io|
io.each { |s| print s }
end
Cheers!
You should use IO#popen:
IO.popen("ping -c 3 google.com") do |data|
while line = data.gets
puts line
end
end
If you'd like to capture both the stdout
and stderr
you can use popen2e
:
require 'open3'
Open3.popen2e('do something') do |_stdin, stdout_err, _wait_thr|
stdout_err.each { |line| puts line }
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With