Feature #1473 ยป expect.patch
ext/pty/lib/expect.rb 2009-05-13 15:50:57.000000000 -0300 | ||
---|---|---|
$expect_verbose = false
|
||
class IO
|
||
def expect(pat,timeout=9999999)
|
||
# Reads ios until pattern matches or the timeout is over. It returns
|
||
# an array with the read buffer, folowed by the matches. If a block is given,
|
||
# the result is yielded to the block and returns nil. The optional timeout parameter defines,
|
||
# in seconds, the total time to wait for pattern. If it is over of eof is found, it
|
||
# returns/yields nil. However, the buffer in a timeout session is kept for the next expect call.
|
||
# The default timeout is 30 seconds.
|
||
def expect(pattern,timeout=30)
|
||
buf = ''
|
||
case pat
|
||
case pattern
|
||
when String
|
||
e_pat = Regexp.new(Regexp.quote(pat))
|
||
pattern = Regexp.new(Regexp.quote(pattern))
|
||
when Regexp
|
||
e_pat = pat
|
||
#pattern = pattern
|
||
else
|
||
raise ArgumentError, "unsupported pattern class: #{pattern.class}"
|
||
end
|
||
@unusedBuf = '' if not @unusedBuf
|
||
starttime = Time.now
|
||
while true
|
||
if !IO.select([self],nil,nil,timeout) or eof? then
|
||
result = nil
|
||
break
|
||
if not @unusedBuf.empty?
|
||
c = @unusedBuf.slice!(0).chr
|
||
else
|
||
remaining = timeout-(Time.new-starttime)
|
||
if remaining <= 0 or !IO.select([self],nil,nil,remaining) or eof? then
|
||
result = nil
|
||
@unusedBuf = buf
|
||
break
|
||
end
|
||
c = getc.chr
|
||
end
|
||
c = getc.chr
|
||
buf << c
|
||
if $expect_verbose
|
||
STDOUT.print c
|
||
STDOUT.flush
|
||
end
|
||
if mat=e_pat.match(buf) then
|
||
if mat=pattern.match(buf) then
|
||
result = [buf,*mat.to_a[1..-1]]
|
||
break
|
||
end
|