一个常见的例程,作个记录。要点在注释里有。
代码:
package main
import (
"fmt"
"os/exec"
"runtime"
"syscall"
)
func main() {
cmd := exec.Command("cmd.exe", "/c", "D:\\docker\\kubectl.exe", "version")
if runtime.GOOS == "windows" {
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
}
//Start执行不会等待命令完成,Run会阻塞等待命令完成。
//err := cmd.Start()
//err := cmd.Run()
//cmd.Output()函数的功能是运行命令并返回其标准输出。
buf, err := cmd.Output()
if err != nil {
if exitErr, ok := err.(*exec.ExitError); ok {
status := exitErr.Sys().(syscall.WaitStatus)
switch {
case status.Exited():
fmt.Printf("Return exit error: exit code=%d\n", status.ExitStatus())
case status.Signaled():
fmt.Printf("Return exit error: signal code=%d\n", status.Signal())
}
} else {
fmt.Printf("Return other error: %s\n", err)
}
} else {
fmt.Printf("Return OK\n")
fmt.Println(string(buf))
}
}
运行:
D:\test\wincmd>wincmd.exe
Return exit error: exit code=1
D:\test\wincmd>wincmd.exe
Return exit error: exit code=1
D:\test\wincmd>wincmd.exe
Return exit error: exit code=1
D:\test\wincmd>wincmd.exe
Return OK
Client Version: version.Info{Major:"1", Minor:"17", GitVersion:"v1.17.4", GitCommit:"8d8aa39598534325ad77120c120a22b3a99
0b5ea", GitTreeState:"clean", BuildDate:"2020-03-12T21:03:42Z", GoVersion:"go1.13.8", Compiler:"gc", Platform:"windows/a
md64"}
Server Version: version.Info{Major:"1", Minor:"17", GitVersion:"v1.17.4-rc2+k3s1", GitCommit:"3eee8ac3a1cf0a216c8a660571
329d4bda3bdf77", GitTreeState:"clean", BuildDate:"2020-03-23T17:50:43Z", GoVersion:"go1.13.8", Compiler:"gc", Platform:"
linux/amd64"}
D:\test\wincmd>wincmd.exe
Return OK
Client Version: version.Info{Major:"1", Minor:"17", GitVersion:"v1.17.4", GitCommit:"8d8aa39598534325ad77120c120a22b3a99
0b5ea", GitTreeState:"clean", BuildDate:"2020-03-12T21:03:42Z", GoVersion:"go1.13.8", Compiler:"gc", Platform:"windows/a
md64"}
Server Version: version.Info{Major:"1", Minor:"17", GitVersion:"v1.17.4-rc2+k3s1", GitCommit:"3eee8ac3a1cf0a216c8a660571
329d4bda3bdf77", GitTreeState:"clean", BuildDate:"2020-03-23T17:50:43Z", GoVersion:"go1.13.8", Compiler:"gc", Platform:"
linux/amd64"}
有疑问加站长微信联系(非本文作者)