這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
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通過相同的方式擷取到返回結果。
仔細看文檔,一切都包含在裡面