golang如何執行指令碼並擷取傳回值

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

golang中如何執行指令碼並擷取傳回值

呼叫指令碼

在golang標準庫中提供了兩種方式可以用來啟動進程呼叫指令碼

第一種是在os庫中的Process類型,Process類型包含一系列方法用來啟動進程並對進程進行操作(參考: https://golang.org/pkg/os/#Process)

第二種是在os/exec庫種通過Cmd類型的各個函數實現對指令碼的調用,實際上Cmd是對Process中各種方法的高層次封裝(參考: https://golang.org/pkg/os/exec/)

樣本使用Process執行指令碼

package mainimport ("fmt""os")func main() {shellPath := "/home/xx/test.sh"argv := make([]string, 1) attr := new(os.ProcAttr)newProcess, err := os.StartProcess(shellPath, argv, attr)  //運行指令碼if err != nil {fmt.Println(err)}fmt.Println("Process PID", newProcess.Pid)processState, err := newProcess.Wait() //等待命令執行完if err != nil {fmt.Println(err)}fmt.Println("processState PID:", processState.Pid())//擷取PIDfmt.Println("ProcessExit:", processState.Exited())//擷取進程是否退出}

使用Cmd執行指令碼

package mainimport ("fmt""os/exec")func main() {shellPath := "/home/xx/test.sh"command := exec.Command(shellPath) //初始化Cmderr := command.Start()//運行指令碼if nil != err {fmt.Println(err)}fmt.Println("Process PID:", command.Process.Pid)err = command.Wait() //等待執行完成if nil != err {fmt.Println(err)}fmt.Println("ProcessState PID:", command.ProcessState.Pid())}

擷取命令傳回值

實際上指令碼或命令執行完後,會將結果返回到ProcessState中的status去, 但是status不是export的,所以我們需要通過一些手段將指令碼傳回值從syscall.WaitStatus找出來

ProcessState定義type ProcessState struct {pid    int                // The process's id.status syscall.WaitStatus // System-dependent status info.rusage *syscall.Rusage}

對於上面使用Cmd的例子,可以在進程退出後可以通過以下語句擷取到傳回值

fmt.Println("Exit Code", command.ProcessState.Sys().(syscall.WaitStatus).ExitStatus())

使用Process方式的也可以通過對ProcessState通過相同的方式擷取到返回結果。

仔細看文檔,一切都包含在裡面

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.