Created
March 23, 2012 03:39
-
-
Save grosser/2166521 to your computer and use it in GitHub Desktop.
Interact with commandline processess via stdin
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
# 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