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


当前回答

backticks(')方法是在Ruby中调用shell命令最简单的方法。它返回shell命令的结果:

     url_request = 'http://google.com'
     result_of_shell_command = `curl #{url_request}`

其他回答

我最喜欢的是Open3

  require "open3"

  Open3.popen3('nroff -man') { |stdin, stdout, stderr| ... }

backticks(')方法是在Ruby中调用shell命令最简单的方法。它返回shell命令的结果:

     url_request = 'http://google.com'
     result_of_shell_command = `curl #{url_request}`

您可以使用如下格式方法打印一些信息:

puts format('%s', `ps`)
puts format('%d MB', (`ps -o rss= -p #{Process.pid}`.to_i / 1024))

不要忘记使用spawn命令创建一个后台进程来执行指定的命令。你甚至可以使用Process类和返回的pid来等待它的完成:

pid = spawn("tar xf ruby-2.0.0-p195.tar.bz2")
Process.wait pid

pid = spawn(RbConfig.ruby, "-eputs'Hello, world!'")
Process.wait pid

文档说:这个方法类似于#system,但它不会等待命令完成。

我们可以通过多种方式来实现它。

使用Kernel#exec命令执行后什么都没有:

exec('ls ~')

使用反引号或%x

`ls ~`
=> "Applications\nDesktop\nDocuments"
%x(ls ~)
=> "Applications\nDesktop\nDocuments"

使用Kernel#system命令,如果成功返回true,不成功返回false,如果命令执行失败返回nil:

system('ls ~')
=> true