Skip to content

Instantly share code, notes, and snippets.

@Donavan
Last active August 29, 2015 14:12
Show Gist options
  • Save Donavan/e5644b3a4608bab91f27 to your computer and use it in GitHub Desktop.
Save Donavan/e5644b3a4608bab91f27 to your computer and use it in GitHub Desktop.
def open3_with_timeout(cmd)
#require 'pry'; binding.pry
inp, out, err, wait_thr = Open3.popen3(cmd)
inp.close
did_timeout = false
still_open = [out, err] # Array that only contains the opened streams
output_buffer = ''
stderr_buffer = ''
output_lines = []
stderr_lines = []
while !still_open.empty?
fhs = select(still_open, nil, nil, 300)
output_lines.concat handle_io(still_open, fhs[0], out, output_buffer) unless fhs.nil?
stderr_lines.concat handle_io(still_open, fhs[0], err, stderr_buffer) unless fhs.nil?
if fhs.nil?
did_timeout = true
still_open.clear
end
# Could easily do something with the data here instead of holding it.
end
out.close
err.close
@logger.error 'Timeout waiting for output from cucumber' if did_timeout
result = did_timeout ? nil : wait_thr.value
return output_lines, stderr_lines, result
end
def handle_io(still_open, io_array, io, buffer)
lines = []
if io_array.include?(io)
begin
buffer << io.readpartial(4096)
have_newline = buffer =~ /([^\n]+)\z/ ? $1 : nil
buffer.scan(/.*\n/) do |line|
lines << line.chomp
end
if have_newline
buffer.replace(have_newline)
else
buffer.clear
end
rescue EOFError
still_open.delete_if{|s| s == io}
end
end
@logger.debug lines
lines
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment