如果我调用一个命令使用内核#系统在Ruby中,我如何得到它的输出?

system("ls")

当前回答

作为直接系统(…)替代品,您可以使用Open3.popen3(…)

进一步讨论: http://tech.natemurray.com/2007/03/ruby-shell-commands.html

其他回答

如果你想使用Kernel#系统将输出重定向到一个文件,你可以这样修改描述符:

以追加模式将stdout和stderr重定向到文件(/tmp/log):

系统(ls状态”,:= > [/ tmp /日志,' '],:呃= > [/ tmp /日志,' '])

对于长时间运行的命令,这将实时存储输出。您还可以使用IO存储输出。管道和重定向它从内核#系统。

我想扩展和澄清一下混沌的答案。

如果你用反勾号包围命令,那么你根本不需要(显式地)调用system()。反勾号执行命令并以字符串形式返回输出。然后你可以像这样把值赋给一个变量:

output = `ls`
p output

or

printf output # escapes newline chars

另一种方法是:

f = open("|ls")
foo = f.read()

注意,这是open中“ls”前面的“pipe”字符。这也可用于将数据送入程序的标准输入以及读取其标准输出。

作为直接系统(…)替代品,您可以使用Open3.popen3(…)

进一步讨论: http://tech.natemurray.com/2007/03/ruby-shell-commands.html

最方便的方法是:

    stdout_str, stderr_str, status = Open3.capture3(cmd)
    puts "exit status: #{status.exitstatus} stdout: #{stdout_str}"