Running an interactive program from Ruby

不问归期 提交于 2019-12-06 02:31:50

I guess this is what you want:

require 'pty'
require 'expect'

PTY.spawn('gnuplot') do |input, output, pid|
  str = input.expect(/gnuplot>/)
  puts str
  output.puts "mlqksdf"

  str = input.expect(/gnuplot>/)
  puts str
  output.puts "exit"
end

The problem is that the sub-program is waiting for input that isn't being sent.

Typically, when we call a program that expects input on STDIN, we have to close STDIN, which then signals that program to begin processing. Look through the various Open3 methods and you'll see where stdin.close occurs in many examples, but they don't explain why.

Open3 also includes capture2 and capture3, which make it nice when trying to deal with a program that wants STDIN and you don't have anything to send to it. In both methods, STDIN is immediately closed, and the method returns the STDOUT, STDERR and exit status of the called program.


You need "expect" functionality. Ruby's Pty class includes an expect method.

Creates and managed pseudo terminals (PTYs). See also en.wikipedia.org/wiki/Pseudo_terminal

It's not very well documented though, and doesn't offer a lot of functionality from what I've seen. An example of its use is available at "Using Ruby Expect Library to Reboot Ruckus Wireless Access Points via ssh".

Instead, you might want to look at RubyExpect which is better documented and appears to be current.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!