用ruby調用執行shell命令


碰到需要調用操作系統shell命令的時候,Ruby為我們提供了六種完成任務的方法:
1.Exec方法:
     Kernel#exec方法通過調用指定的命令取代當前進程:
  例子:
      $ irb
      >> exec 'echo "hello $HOSTNAME"'
         hello nate.local
      $
值得注意的是,exec方法用echo命令來取代了irb進程從而退出了irb。主要的缺點是,你無法從你的ruby腳本里知道這個命令是成功還是失敗。
 
2.System方法。
  Kernel#system方法操作命令同上, 但是它是運行一個子shell來避免覆蓋當前進程。如果命令執行成功則返回true,否則返回false。
 
 $ irb             
  >> system 'echo "hello $HOSTNAME"'
  hello nate.local
  => true
  >> system 'false' 
  => false
  >> puts $?
  256
  => nil
  >> 
3.反引號(Backticks,Esc鍵下面那個鍵)
$ irb
  >> today = `date`
  => "Mon Mar 12 18:15:35 PDT 2007n" 
  >> $?
  => #<Process::Status: pid=25827,exited(0)>
  >> $?.to_i
  => 0
這種方法是最普遍的用法了。它也是運行在一個子shell中。
4.IO#popen
  $ irb
  >> IO.popen("date") { |f| puts f.gets }
  Mon Mar 12 18:58:56 PDT 2007
  => nil
5.open3#popen3
$ irb
  >> stdin, stdout, stderr = Open3.popen3('dc') 
  => [#<IO:0x6e5474>, #<IO:0x6e5438>, #<IO:0x6e53d4>]
  >> stdin.puts(5)
  => nil
  >> stdin.puts(10)
  => nil
  >> stdin.puts("+")
  => nil
  >> stdin.puts("p")
  => nil
  >> stdout.gets
  => "15n"
6.Open4#popen4
$ irb
  >> require "open4" 
  => true
  >> pid, stdin, stdout, stderr = Open4::popen4 "false" 
  => [26327, #<IO:0x6dff24>, #<IO:0x6dfee8>, #<IO:0x6dfe84>]
  >> $?
  => nil
  >> pid
  => 26327
  >> ignored, status = Process::waitpid2 pid
  => [26327, #<Process::Status: pid=26327,exited(1)>]
  >> status.to_i
  => 256


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM