我需要在命令行上运行一个命令来请求用户响应。如果它有帮助,命令是:
gpg --recipient "Some Name" --encrypt ~/some_file.txt
当你运行它时,它会发出警告然后询问:
Use this key anyway? (y/N)
响应“y”让它正确完成。我一直在尝试使用 open4 gem但我无法让它正确指定“y”。这是我尝试过的:
Open4::popen4(cmd) do |pid, stdin, stdout, stderr|
stdin.puts "y"
stdin.close
puts "pid : #{ pid }"
puts "stdout : #{ stdout.read.strip }"
puts "stderr : #{ stderr.read.strip }"
end
我做错了什么?我正在做的事情有可能吗?
最佳答案
处理这些情况的 Unix 方法是使用 expect , Ruby 自带 built-in support对于:
require 'pty'
require 'expect'
PTY.spawn("your command here") do |reader, writer|
reader.expect(/Use this key anyway/, 5) # cont. in 5s if input doesn't match
writer.puts('y')
puts "cmd response: #{reader.gets}"
end
关于ruby - 在 ruby 中运行系统命令并与之交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10645173/