Running an interactive program from Ruby

I am trying to run gnuplot from ruby ​​(not using external gem) and parsing its text output. I've tried IO.popen

, PTY.spawn

and Open3.popen3

, but whenever I try to get output, it just "hangs" - I guess I'm waiting for more output to come. It seems to me that it is somehow done with help Thread.new

, but I couldn't find the correct way to implement it.

Does anyone know how this is done?

+3


source to share


2 answers


I think 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

      

+3


source


The problem is that the routine is expecting input that is not being sent.

Typically, when we call a program that is waiting for input on STDIN, we must close STDIN, which then signals that the program will start processing. Browse through the various Open3 methods and you will see where stdin.close

it appears in many examples, but they do not explain why.

Open3 also includes capture2

and capture3

, which makes it enjoyable when trying to deal with a program that wants STDIN and you have nothing to send anything. In both methods, STDIN is immediately closed and the method returns STDOUT, STDERR, and the exit status of the called program.




You need a "wait" function. The Ruby Pty class includes a method expect

.

Creates and manages pseudo-terminals (PTYs). See also ru.wikipedia.org/wiki/Pseudo_terminal

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

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

+1


source







All Articles