Is there an Expect equivalent gem for Ruby?

前端 未结 6 676
一生所求
一生所求 2020-12-05 14:16

Is there an Expect equivalent gem for Ruby?

I tried searching on code.google and rubygems.org, but sadly it did not show up.

FYI: Expect is a Unix automation

6条回答
  •  失恋的感觉
    2020-12-05 14:51

    I recently spent quite a bit of time struggling with this issue (I am stuck with 1.8.7). I found this question, this blog post and this forum thread really useful.

    At the end this is my application code if anyone is interested in a little example (pass the password to rpm when signing packages):

    def run_interactive command, password, promt
      output   = ''
      begin
        r, w, pid = PTY.spawn(command)
        puts r.expect(promt)
        sleep(0.5)
        w.puts(password)
        begin
          r.each { |l| output += l } 
        rescue Errno::EIO
        end
        $?.exitstatus
        Process.wait(pid)
      rescue PTY::ChildExited => e
        $stderr.puts "The child process #{e} exited! #{$!.status.exitstatus}"
      end 
      output
    end
    
    password = "mypassword"
    command  = "rpm --define '_signature gpg' --define '_gpg_name #{key_id}' --addsign #{package}"
    promt    = %r{.*: }
    expected = %r{good}
    output = run_interactive(command, password, promt)
    if output.match(expected)
      puts output
    else
      abort "Error: expected: '#{expected}' got '#{output}'"
    end 
    

    It has little error checking but it was all I needed.

    Edit: Update the code with Process.wait(pid) to make sure it finishes before continuing and add comment about this being for 1.8.7.

提交回复
热议问题