Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/lib/expect.rb
Views: 11704
# Sourced from Ruby's ext/pty/lib/expect.rb to allow for access from Windows,1# which does not seem to have an issue using this particular method with2# sockets (pipes and other handles won't work, so don't use it for that).3# frozen_string_literal: true4$expect_verbose = false56# Expect library adds the IO instance method #expect, which does similar act to7# tcl's expect extension.8#9# In order to use this method, you must require expect:10#11# require 'expect'12#13# Please see #expect for usage.14class IO15# call-seq:16# IO#expect(pattern,timeout=9999999) -> Array17# IO#expect(pattern,timeout=9999999) { |result| ... } -> nil18#19# Reads from the IO until the given +pattern+ matches or the +timeout+ is over.20#21# It returns an array with the read buffer, followed by the matches.22# If a block is given, the result is yielded to the block and returns nil.23#24# When called without a block, it waits until the input that matches the25# given +pattern+ is obtained from the IO or the time specified as the26# timeout passes. An array is returned when the pattern is obtained from the27# IO. The first element of the array is the entire string obtained from the28# IO until the pattern matches, followed by elements indicating which the29# pattern which matched to the anchor in the regular expression.30#31# The optional timeout parameter defines, in seconds, the total time to wait32# for the pattern. If the timeout expires or eof is found, nil is returned33# or yielded. However, the buffer in a timeout session is kept for the next34# expect call. The default timeout is 9999999 seconds.35def expect(pat,timeout=9999999)36buf = ''.dup37case pat38when String39e_pat = Regexp.new(Regexp.quote(pat))40when Regexp41e_pat = pat42else43raise TypeError, "unsupported pattern class: #{pat.class}"44end45@unusedBuf ||= ''46while true47if not @unusedBuf.empty?48c = @unusedBuf.slice!(0)49elsif !IO.select([self],nil,nil,timeout) or eof? then50result = nil51@unusedBuf = buf52break53else54c = getc55end56buf << c57if $expect_verbose58STDOUT.print c59STDOUT.flush60end61if mat=e_pat.match(buf) then62result = [buf,*mat.captures]63break64end65end66if block_given? then67yield result68else69return result70end71nil72end73end747576