2

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?

0

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

6 Comments

I'm reluctant to use your code because I have no experience with thread synchronization in Ruby. Basically, I just want to be able to process output programmatically and to interact with the shell while I'm at it. Isn't there a simpler way to do that? What if I launch the shell and redirect a copy of output with tee to my program? Will it solve my problem?
@ArtShayderov I've updated the demo a bit and added some comment. You can save it to a Ruby file and test it. It should be clear where to manipulate the standard input and where to process the standard output now.
So I put reading STDIN inside tin block like that STDIN.each_char {|c| i.puts c}?
@ArtShayderov Yes. Make sure 1) You terminate the input by EOF after you finish typing, that is, Ctrl-Z on windows or Ctrl-D on Linux. 2) You close the standard input of the child process (i.close) before you leave the tin block.
It works. But I'm testing different commands in linux and some of them (e.g. top) fail with message failed tty get.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.