如果我调用一个命令使用内核#系统在Ruby中,我如何得到它的输出?
system("ls")
如果我调用一个命令使用内核#系统在Ruby中,我如何得到它的输出?
system("ls")
当前回答
作为直接系统(…)替代品,您可以使用Open3.popen3(…)
进一步讨论: http://tech.natemurray.com/2007/03/ruby-shell-commands.html
其他回答
puts `date`
puts $?
Mon Mar 7 19:01:15 PST 2016
pid 13093 exit 0
作为直接系统(…)替代品,您可以使用Open3.popen3(…)
进一步讨论: http://tech.natemurray.com/2007/03/ruby-shell-commands.html
我想扩展和澄清一下混沌的答案。
如果你用反勾号包围命令,那么你根本不需要(显式地)调用system()。反勾号执行命令并以字符串形式返回输出。然后你可以像这样把值赋给一个变量:
output = `ls`
p output
or
printf output # escapes newline chars
如果你需要转义参数,在Ruby 1.9 IO中。Popen也接受数组:
p IO.popen(["echo", "it's escaped"]).read
在早期版本中,你可以使用Open3.popen3:
require "open3"
Open3.popen3("echo", "it's escaped") { |i, o| p o.read }
如果你还需要传递stdin,这应该在1.9和1.8中都有效:
out = IO.popen("xxd -p", "r+") { |io|
io.print "xyz"
io.close_write
io.read.chomp
}
p out # "78797a"
只是为了记录,如果你想要(输出和操作结果),你可以这样做:
output=`ls no_existing_file` ; result=$?.success?