如何从Ruby程序内部调用shell命令?然后如何将这些命令的输出返回到Ruby中?


当前回答

上面的答案已经非常棒了,但是我真的很想分享下面的总结文章:“在Ruby中运行Shell命令的6种方法”

基本上,它告诉我们:

# exec内核:

exec 'echo "hello $HOSTNAME"'

System和$?:

system 'false' 
puts $?

Backticks ():

today = `date`

IO # execlp:

IO.popen("date") { |f| puts f.gets }

Open3#popen3—stdlib:

require "open3"
stdin, stdout, stderr = Open3.popen3('dc') 

Open4#popen4—一个宝石:

require "open4" 
pid, stdin, stdout, stderr = Open4::popen4 "false" # => [26327, #<IO:0x6dff24>, #<IO:0x6dfee8>, #<IO:0x6dfe84>]

其他回答

还有一个选择:

当你:

需要stderr和stdout 不能/不会使用Open3/Open4(他们在我的Mac上的NetBeans中抛出异常,不知道为什么)

你可以使用shell重定向:

puts %x[cat bogus.txt].inspect
  => ""

puts %x[cat bogus.txt 2>&1].inspect
  => "cat: bogus.txt: No such file or directory\n"

从MS-DOS的早期开始,2>&1语法就适用于Linux、Mac和Windows。

我绝对不是Ruby专家,但我还是会试一试:

$ irb 
system "echo Hi"
Hi
=> true

你还应该能够做以下事情:

cmd = 'ls'
system(cmd)

最简单的方法是:

reboot = `init 6`
puts reboot

不确定shell命令。我使用以下命令将系统命令的输出捕获到变量val中:

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

puts val

缩短版本:

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

捕获方法由active_support/core_ext/kernel/reporting.rb提供

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

你也可以使用反勾操作符('),类似于Perl:

directoryListing = `ls /`
puts directoryListing # prints the contents of the root directory

如果你需要简单的东西,很方便。

你想要使用哪种方法取决于你想要完成什么;有关不同方法的更多细节,请查看文档。