在ruby中运行shell命令,将STDIN附加到命令输入

时间:2014-04-20 13:15:57

标签: ruby shell

我在ruby脚本中运行一个长时间运行的shell命令,如下所示:

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

所以我可以在shell窗口中查看命令输出。

如何将STDIN附加到命令输入?

1 个答案:

答案 0 :(得分:1)

你需要:

  1. 等待来自STDIN的用户输入
  2. 等待popen3 -- o
  3. 输出命令

    您可能需要IO.select或其他IO调度程序,或其他一些多任务调度程序,例如Thread

    以下是Thread方法的演示:

    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