美文网首页
linux下,ruby调用系统命令

linux下,ruby调用系统命令

作者: kamionayuki | 来源:发表于2015-06-28 19:43 被阅读771次
  • exec
    Kernel#exec方法通过调用指定的命令取代当前进程例子:
    exec "pwd"
    puts 1

值得注意的是,exec方法用echo命令来取代了irb进程从而退出了irb。主要的缺点是,你无法从你的ruby脚本里知道这个命令是成功还是失败。也就是说上面的脚本puts 1是不会执行的。因为当执行完exec后,就退出了。

  • system
    Kernel#system方法操作命令同上, 但是它是运行一个子shell来避免覆盖当前进程。如果命令执行成功则返回true,否则返回false。
    system "pwd"
    puts 1
  • 反引号
    最普遍的用法了。它也是运行在一个子shell中。基本类似system
    puts `pwd`
    puts 1
  • IO#popen
    begin
      IO.popen("mv -v #{$*[0]} #{$*[1]}")  {|output| puts output.gets}
    rescue Exception => e
      puts $!
    end
    puts 1
  • open3#popen3
    require 'open3'
    begin
      #如果不想输出任何内容,直接用下面代码即可
      string = 'pwd'
      Open3.popen3(string) do |tdin, stdout, stderr, thread|
      end
    rescue Exception => e
      puts $!
    end
    puts 1

open3还有一个方法popen2e,是将stdoutstderr合在一起了。我们可以用下面的代码来判断命令是否运行成功,如果失败了,则打印stdout或者stderr。

   require 'open3'
   begin
     string = 'pwd'
     Open3.popen2e(string) do |_, out, thread|
       exit_status = thread.value # Process::Status object returned.  
       puts out.read.chomp unless exit_status.success?
     end
   rescue Exception => e
     puts $!
   end
  • Open4#popen4

相关文章

网友评论

      本文标题:linux下,ruby调用系统命令

      本文链接:https://www.haomeiwen.com/subject/jymeqttx.html