Created
December 6, 2017 21:36
-
-
Save rx/3a9a2a2c7ca8020bdbe2364cc6b0c240 to your computer and use it in GitHub Desktop.
Slick IO error handling for ruby shelled commands:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# From: https://nickcharlton.net/posts/ruby-subprocesses-with-stdout-stderr-streams.html | |
require 'open3' | |
module Utils | |
class Subprocess | |
def initialize(cmd, &block) | |
# see: http://stackoverflow.com/a/1162850/83386 | |
Open3.popen3(cmd) do |stdin, stdout, stderr, thread| | |
# read each stream from a new thread | |
{ :out => stdout, :err => stderr }.each do |key, stream| | |
Thread.new do | |
until (line = stream.gets).nil? do | |
# yield the block depending on the stream | |
if key == :out | |
yield line, nil, thread if block_given? | |
else | |
yield nil, line, thread if block_given? | |
end | |
end | |
end | |
end | |
thread.join # don't exit until the external process is done | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment