用ruby呼叫執行shell命令

2022-02-06 19:18:00 字數 1508 閱讀 8312

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

>> $?

=> #

>> $?.to_i

=> 0

這種方法是最普遍的用法了。它也是執行在乙個子shell中。

4.io#popen

$ irb

>> io.popen("date")

mon mar 12 18:58:56 pdt 2007

=> nil

5.open3#popen3

$ irb

>> stdin, stdout, stderr = open3.popen3('dc') 

=> [#, #, #]

>> 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, #, #, #]

>> $?

=> nil

>> pid

=> 26327

>> ignored, status = process::waitpid2 pid

=> [26327, #]

>> status.to_i

=> 256

六種用ruby呼叫執行shell命令的方法

原始出處 作者資訊和本宣告。否則將追究法律責任。碰到需要呼叫作業系統shell命令的時候,ruby為我們提供了六種完成任務的方法 1.exec方法 kernel exec方法通過呼叫指定的命令取代當前程序 例子 irb exec echo hello hostname hello nate.loca...

ruby呼叫linux的shell方法

碰到需要呼叫作業系統shell命令的時候,ruby為我們提供了六種完成任務的方法 1.exec方法 kernel exec方法通過呼叫指定的命令取代當前程序 例子 irb exec echo hello hostname hello nate.local 值得注意的是,exec方法用echo命令來取...

Python基礎 呼叫shell和cmd命令

啟動 catcmd adb s tvip 5555 logcat v time logpath printcatcmd self lcprocess subprocess.popen catcmd stdout subprocess.pipe stderr subprocess.pipe shell...