golang如何執行腳本並獲取返回值

golang中如何執行腳本並獲取返回值

調用腳本

在golang標準庫中提供了兩種方式能夠用來啓動進程調用腳本golang

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

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

示例 使用Process執行腳本code

package main

import (
	"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())//獲取PID
	fmt.Println("ProcessExit:", processState.Exited())//獲取進程是否退出
}

使用Cmd執行腳本進程

package main

import (
	"fmt"
	"os/exec"
)

func main() {
	shellPath := "/home/xx/test.sh"
	command := exec.Command(shellPath) //初始化Cmd
	err := 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的例子,能夠在進程退出後能夠經過如下語句獲取到返回值get

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

使用Process方式的也能夠經過對ProcessState經過相同的方式獲取到返回結果。string

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

相關文章
相關標籤/搜索