Skip to content

Instantly share code, notes, and snippets.

@cataphract
Created July 15, 2014 09:56
Show Gist options
  • Save cataphract/97695c1bda1c788e7bf2 to your computer and use it in GitHub Desktop.
Save cataphract/97695c1bda1c788e7bf2 to your computer and use it in GitHub Desktop.
def run_command(command)
Open3.popen3(*command) do |stdin, stdout, stderr, wait_thr|
stdin.close_write
files = [stdout, stderr]
all_eof = lambda { files.all? { |f| f.eof } }
print_lines = lambda { |buffer, method|
while pos = buffer.index("\n")
Log.send method, buffer[0..pos]
buffer = buffer[(pos + 1)..-1]
end
buffer
}
stdout_buffer = ''
stderr_buffer = ''
until all_eof[] do
ready = IO.select(files)
next if !ready or ready[0].empty?
ready[0].each do |f|
begin
data = f.read_nonblock(1024)
if f == stdout
stdout_buffer << data
else
stderr_buffer << data
end
rescue EOFError => e
end
end
stdout_buffer = print_lines[stdout_buffer, 'info']
stderr_buffer = print_lines[stderr_buffer, 'err']
end
wait_thr.value
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment