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

标签 ruby shell

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

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

这样我就可以在 shell 窗口中查看命令输出。

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

最佳答案

你需要:

  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

关于ruby - 在 ruby​​ 中运行 shell 命令,将 STDIN 附加到命令输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23182902/

相关文章:

ruby - cucumber 测试的运行顺序是什么

ruby-on-rails - 用蜻蜓保存 TinyMCE Base64 图像

mysql - 如何在 MYSQL Shell 中执行我的 sql 迁移脚本?

shell - shell 文件中的“mkdir”无法创建目录 : "Permission denied"

amazon-web-services - 如何使用 shell 脚本列出未使用的 AWS S3 存储桶和空存储桶?

shell - 提取其中一列中的值等于另一列中的值 +1 的行?

linux - 如何逐行读取文件并将每一行重定向到 shell 脚本中的变量?

ruby-on-rails - 在 Rails 3 中路由嵌套资源

ruby - yard,如何将图像包含到文档中?

ruby - 是否有使用普通 ruby​​ 对象并且不需要您从基类继承的 Ruby ORM?