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

system("ls")

当前回答

你可以用反勾号:

`ls`

其他回答

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

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

请注意,所有向系统传递包含用户提供值的字符串的解决方案,%x[]等都是不安全的!不安全实际上意味着:用户可以触发代码在上下文中运行,并具有程序的所有权限。

据我所知,只有系统和Open3。popen3在Ruby 1.8中提供了一个安全/转义的变体。在Ruby 1.9中,IO::popen也接受数组。

只需将每个选项和参数作为数组传递给其中一个调用。

如果你不仅需要退出状态,还需要结果,你可能会使用Open3.popen3:

require 'open3'
stdin, stdout, stderr, wait_thr = Open3.popen3('usermod', '-p', @options['shadow'], @options['username'])
stdout.gets(nil)
stdout.close
stderr.gets(nil)
stderr.close
exit_code = wait_thr.value

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

更多信息:在Ruby中形成卫生shell命令或系统调用

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

你可以用反勾号:

`ls`
puts `date`
puts $?


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