golang下的os/exec包執行外部命令,它將os.StartProcess進行包裝使得它更容易映射到stdin和stdout。這點和python下的command、os.system等功能是同樣的。這裏列兩個具體操做的代碼。其能夠調用類LINUX系統下的shell命令,也能夠在windows下調用cmd下的命令。html
代碼一python
package main import ( "bytes" "fmt" "log" "os/exec" ) const ShellToUse = "bash" func Shellout(command string) (error, string, string) { var stdout bytes.Buffer var stderr bytes.Buffer cmd := exec.Command(ShellToUse, "-c", command) cmd.Stdout = &stdout cmd.Stderr = &stderr err := cmd.Run() return err, stdout.String(), stderr.String() } func main() { err, out, errout := Shellout("ls -ltr") if err != nil { log.Printf("error: %v\n", err) } fmt.Println("--- stdout ---") fmt.Println(out) fmt.Println("--- stderr ---") fmt.Println(errout) }
以上代碼執行後,效果以下:linux
[root@361way go] go run cmd.go --- stdout --- total 24 drwxr-xr-x 6 root root 79 Jun 13 2017 src -rw-r--r-- 1 root root 752 Aug 19 10:55 login.go -rw-r--r-- 1 root root 1189 Aug 19 14:29 log.go -rw-r--r-- 1 root root 623 Aug 19 16:43 cmd.go -rw-r--r-- 1 root root 538 Aug 19 17:41 cmd2.go -rw-r--r-- 1 root root 519 Aug 19 21:38 http.go -rw-r--r-- 1 root root 462 Aug 19 22:29 test.py --- stderr ---
代碼二golang
package main import ( "fmt" "os/exec" ) func Cmd(cmd string, shell bool) []byte { if shell { out, err := exec.Command("bash", "-c", cmd).Output() if err != nil { panic("some error found") } return out } else { out, err := exec.Command(cmd).Output() if err != nil { panic("some error found") } return out } } func main() { //cmd := "ls -al" cmd := "python test.py" //cmd := "python -V" //沒有輸出 //cmd := "env" out := string(Cmd(cmd,true)) //out := string(Cmd(cmd,false)) fmt.Println(out) }
由於都是調用的exec.Command方法並調用bash shell,本質上並無什麼區別。其也能夠正常調用python腳本,但在直接調用python -V命令時沒有輸出,這點感受很奇怪。shell
原文來自: https://www.linuxprobe.com/golang-exec-command.htmlwindows