Ruby中調用執行shell命令的6種方法_ruby專題

來源:互聯網
上載者:User

碰到需要叫用作業系統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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.