如果我调用一个命令使用内核#系统在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-否则它们必须显式关闭。
其他回答
只是为了记录,如果你想要(输出和操作结果),你可以这样做:
output=`ls no_existing_file` ; result=$?.success?
我在这里没有找到这个,所以添加它,我有一些问题得到完整的输出。
您可以重定向STDERR到STDOUT,如果您想捕获STDERR使用 撇号。 输出= ' grep hosts /private/etc/* 2>&1 '
来源:http://blog.bigbinary.com/2012/10/18/backtick-system-exec-in-ruby.html
你可以用反勾号:
`ls`
作为直接系统(…)替代品,您可以使用Open3.popen3(…)
进一步讨论: http://tech.natemurray.com/2007/03/ruby-shell-commands.html
另一种方法是:
f = open("|ls")
foo = f.read()
注意,这是open中“ls”前面的“pipe”字符。这也可用于将数据送入程序的标准输入以及读取其标准输出。