linux下,ruby调用系统命令

2015-06-28  本文已影响771人  kamionayuki
    exec "pwd"
    puts 1

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

    system "pwd"
    puts 1
    puts `pwd`
    puts 1
    begin
      IO.popen("mv -v #{$*[0]} #{$*[1]}")  {|output| puts output.gets}
    rescue Exception => e
      puts $!
    end
    puts 1
    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
上一篇 下一篇

猜你喜欢

热点阅读