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

system("ls")

当前回答

将标准输出捕获到名为val的变量中最简单的解决方案:

val = capture(:stdout) do
  system("pwd")
end

puts val

缩短版本:

val = capture(:stdout) { system("ls") }

捕获方法由 active_support / core_ext /内核/ reporting.rb

类似地,我们也可以用:stderr捕获标准错误

其他回答

你可以用反勾号:

`ls`
puts `date`
puts $?


Mon Mar  7 19:01:15 PST 2016
pid 13093 exit 0

另一种方法是:

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

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

你可以使用一个叫做Frontkick的宝石

Frontkick.exec("echo *")

下面是如何检查和阅读它:

result = Frontkick.exec("echo *")

puts result.successful? #=> true if exit_code is 0
puts result.success?    #=> alias to successful?, for compatibility with Process::Status
puts result.stdout      #=> stdout output of the command
puts result.stderr      #=> stderr output of the command
puts result.exit_code   #=> exit_code of the command
puts result.status      #=> alias to exit_code
puts result.exitstatus  #=> alias to exit_code, for compatibility with Process::Status
puts result.duration    #=> the time used to execute the command

Github https://github.com/sonots/frontkick frontkick

创业板页面https://rubygems.org/gems/frontkick

您可以使用system()或%x[],这取决于您需要什么样的结果。

System()如果找到命令并成功运行,则返回true,否则返回false。

>> s = system 'uptime'
10:56  up 3 days, 23:10, 2 users, load averages: 0.17 0.17 0.14
=> true
>> s.class
=> TrueClass
>> $?.class
=> Process::Status

% x [. .]另一方面,将命令的结果保存为字符串:

>> result = %x[uptime]
=> "13:16  up 4 days,  1:30, 2 users, load averages: 0.39 0.29 0.23\n"
>> p result 
"13:16  up 4 days,  1:30, 2 users, load averages: 0.39 0.29 0.23\n"
>> result.class
=> String

Jay Fields的博客文章详细解释了system、exec和%x[..]]。