linux下,ruby调用系统命令

  • 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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容