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

system("ls")

当前回答

如果你需要转义参数,在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"

其他回答

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

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

puts val

缩短版本:

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

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

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

你可以用反勾号:

`ls`

正如Simon Hürlimann已经解释过的,Open3比反撇号等更安全。

require 'open3'
output = Open3.popen3("ls") { |stdin, stdout, stderr, wait_thr| stdout.read }

注意,块表单将自动关闭stdin, stdout和stderr-否则它们必须显式关闭。

你可以使用一个叫做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

最方便的方法是:

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