Skip to content

Instantly share code, notes, and snippets.

@grosser
Created March 23, 2012 03:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grosser/2166521 to your computer and use it in GitHub Desktop.
Save grosser/2166521 to your computer and use it in GitHub Desktop.
Interact with commandline processess via stdin
# capture commandline output and send responses if nothing was read
def interact(command, answers)
puts command
line = ""
write = false
PTY.spawn(command) do |output, input, pid|
loop do
rs, ws, = IO.select([output], [input])
# read into the buffer
if r = rs[0]
write = false
ret = r.read(1)
print ret
return unless ret
line << ret
line = "" if ret == "\n"
end
# time to write ?
if w = ws[0]
if write and line != ""
text = line.gsub(/\e\[\d+m/,'').strip
answer = answers.detect do |question, answer|
text =~ question
end || raise("Question #{text.inspect} has no answer!")
w.write(answer.last + "\n")
line = ""
else
write = true
end
end
end
end
$?.success?
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment