| 1 |
1 |
$expect_verbose = false
|
| 2 |
2 |
|
| 3 |
3 |
class IO
|
| 4 |
|
def expect(pat,timeout=9999999)
|
|
4 |
|
|
5 |
# Reads ios until pattern matches or the timeout is over. It returns
|
|
6 |
# an array with the read buffer, folowed by the matches. If a block is given,
|
|
7 |
# the result is yielded to the block and returns nil. The optional timeout parameter defines,
|
|
8 |
# in seconds, the total time to wait for pattern. If it is over of eof is found, it
|
|
9 |
# returns/yields nil. However, the buffer in a timeout session is kept for the next expect call.
|
|
10 |
# The default timeout is 30 seconds.
|
|
11 |
def expect(pattern,timeout=30)
|
| 5 |
12 |
buf = ''
|
| 6 |
|
case pat
|
|
13 |
case pattern
|
| 7 |
14 |
when String
|
| 8 |
|
e_pat = Regexp.new(Regexp.quote(pat))
|
|
15 |
pattern = Regexp.new(Regexp.quote(pattern))
|
| 9 |
16 |
when Regexp
|
| 10 |
|
e_pat = pat
|
|
17 |
#pattern = pattern
|
|
18 |
else
|
|
19 |
raise ArgumentError, "unsupported pattern class: #{pattern.class}"
|
| 11 |
20 |
end
|
|
21 |
@unusedBuf = '' if not @unusedBuf
|
|
22 |
starttime = Time.now
|
| 12 |
23 |
while true
|
| 13 |
|
if !IO.select([self],nil,nil,timeout) or eof? then
|
| 14 |
|
result = nil
|
| 15 |
|
break
|
|
24 |
if not @unusedBuf.empty?
|
|
25 |
c = @unusedBuf.slice!(0).chr
|
|
26 |
else
|
|
27 |
remaining = timeout-(Time.new-starttime)
|
|
28 |
if remaining <= 0 or !IO.select([self],nil,nil,remaining) or eof? then
|
|
29 |
result = nil
|
|
30 |
@unusedBuf = buf
|
|
31 |
break
|
|
32 |
end
|
|
33 |
c = getc.chr
|
| 16 |
34 |
end
|
| 17 |
|
c = getc.chr
|
| 18 |
35 |
buf << c
|
| 19 |
36 |
if $expect_verbose
|
| 20 |
37 |
STDOUT.print c
|
| 21 |
38 |
STDOUT.flush
|
| 22 |
39 |
end
|
| 23 |
|
if mat=e_pat.match(buf) then
|
|
40 |
if mat=pattern.match(buf) then
|
| 24 |
41 |
result = [buf,*mat.to_a[1..-1]]
|
| 25 |
42 |
break
|
| 26 |
43 |
end
|