如果我调用一个命令使用内核#系统在Ruby中,我如何得到它的输出?
system("ls")
如果我调用一个命令使用内核#系统在Ruby中,我如何得到它的输出?
system("ls")
当前回答
正如Simon Hürlimann已经解释过的,Open3比反撇号等更安全。
require 'open3'
output = Open3.popen3("ls") { |stdin, stdout, stderr, wait_thr| stdout.read }
注意,块表单将自动关闭stdin, stdout和stderr-否则它们必须显式关闭。
其他回答
我发现下面是有用的,如果你需要返回值:
result = %x[ls]
puts result
我特别想列出我的机器上所有Java进程的pid,并使用以下方法:
ids = %x[ps ax | grep java | awk '{ print $1 }' | xargs]
只是为了记录,如果你想要(输出和操作结果),你可以这样做:
output=`ls no_existing_file` ; result=$?.success?
如果你想使用Kernel#系统将输出重定向到一个文件,你可以这样修改描述符:
以追加模式将stdout和stderr重定向到文件(/tmp/log):
系统(ls状态”,:= > [/ tmp /日志,' '],:呃= > [/ tmp /日志,' '])
对于长时间运行的命令,这将实时存储输出。您还可以使用IO存储输出。管道和重定向它从内核#系统。
作为直接系统(…)替代品,您可以使用Open3.popen3(…)
进一步讨论: http://tech.natemurray.com/2007/03/ruby-shell-commands.html
如果你需要转义参数,在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"