Art Shayderov
Art Shayderov

Reputation: 5110

Run shell command inside ruby, attach STDIN to command input

I'm running a long-running shell command inside ruby script like this:

Open3.popen2(command) {|i,o,t|
  while line = o.gets
   MyRubyProgram.read line
   puts line
  end
}

So I would be able to look at the command output in the shell window.

How do I attach STDIN to command input?

Upvotes: 2

Views: 2060

Answers (1)

Arie Xiao
Arie Xiao

Reputation: 14082

You need to:

  1. Wait for the user input from STDIN
  2. Wait for the output of the command from the popen3 -- o

You may need IO.select or other IO scheduler, or some other multi-task scheduler, such as Thread.

Here is a demo for the Thread approach:

require 'open3'

Open3.popen3('ruby -e "while line = gets; print line; end"') do |i, o, t|
  tin = Thread.new do
    # here you can manipulate the standard input of the child process
    i.puts "Hello"
    i.puts "World"
    i.close
  end

  tout = Thread.new do
    # here you can fetch and process the standard output of the child process
    while line = o.gets
      print "COMMAND => #{line}"
    end
  end

  tin.join    # wait for the input thread
  tout.join   # wait for the output thread
end

Upvotes: 1

Related Questions