在ruby中运行系统命令并与其交互 [英] Run system command in ruby and interact with it
本文介绍了在ruby中运行系统命令并与其交互的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在命令行上运行一个命令,请求用户响应。如果它帮助命令是:
I need to run a command on the command-line that asks for a user response. In case it helps the command is:
gpg --recipient "Some Name" --encrypt ~/some_file.txt
当你运行这个时,它警告一些东西,然后询问:
when you run this, it warns about something then asks:
仍然使用此键? (y / N)
Use this key anyway? (y/N)
回应'y'让我们正确完成。我一直在尝试使用 open4 gem ,但我无法获得它指定'y '正确。这是我尝试:
Responding 'y' let's it finish correctly. I have been trying to use the open4 gem but I have not been able to get it to specify the 'y' correctly. Here is what I tried:
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提供内置支持:
The Unix way to handle these situations is with expect, which Ruby comes with built-in support for:
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中运行系统命令并与其交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文