我在 ruby 脚本中运行一个长时间运行的 shell 命令,如下所示:
Open3.popen2(command) {|i,o,t|
while line = o.gets
MyRubyProgram.read line
puts line
end
}
这样我就可以在 shell 窗口中查看命令输出。
如何将 STDIN 附加到命令输入?
最佳答案
你需要:
- 等待来自 STDIN 的用户输入
- 等待
popen3 -- o
命令的输出
您可能需要 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/