Skip to content

Instantly share code, notes, and snippets.

@jamiehodge
Last active December 13, 2015 23:49
Show Gist options
  • Save jamiehodge/4994171 to your computer and use it in GitHub Desktop.
Save jamiehodge/4994171 to your computer and use it in GitHub Desktop.
Stream and capture subprocess stdout
require 'open3'
def subprocess(*cmd)
Open3.popen3(*cmd) {|i,o,e,t|
out = Thread.new do
o.each_with_object([]) do |line,memo|
memo << line
yield line if block_given?
end.join
end
err = Thread.new {e.read}
i.close
[out.value, err.value, t.value]
}
end
p subprocess('man', 'ls') {|l| p l}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment