golang执行系统command
golang下的os/exec包执行外部命令,它将os.StartProcess进行包装使得它更容易映射到stdin和stdout。这点和python下的command、os.system等功能是一样的。这里列两个具体操作的代码。其可以调用类LINUX系统下的shell命令,也可以在windows下调用cmd下的命令。
Linux下执行命令的方法
代码一
1package main
2import (
3 "bytes"
4 "fmt"
5 "log"
6 "os/exec"
7)
8const ShellToUse = "bash"
9func Shellout(command string) (error, string, string) {
10 var stdout bytes.Buffer
11 var stderr bytes.Buffer
12 cmd := exec.Command(ShellToUse, "-c", command)
13 cmd.Stdout = &stdout
14 cmd.Stderr = &stderr
15 err := cmd.Run()
16 return err, stdout.String(), stderr.String()
17}
18func main() {
19 err, out, errout := Shellout("ls -ltr")
20 if err != nil {
21 log.Printf("error: %v\n", err)
22 }
23 fmt.Println("--- stdout ---")
24 fmt.Println(out)
25 fmt.Println("--- stderr ---")
26 fmt.Println(errout)
27}
以上代码执行后,效果如下:
[root@361way go] go run cmd.go
1--- stdout ---
2total 24
3drwxr-xr-x 6 root root 79 Jun 13 2017 src
4-rw-r--r-- 1 root root 752 Aug 19 10:55 login.go
5-rw-r--r-- 1 root root 1189 Aug 19 14:29 log.go
6-rw-r--r-- 1 root root 623 Aug 19 16:43 cmd.go
7-rw-r--r-- 1 root root 538 Aug 19 17:41 cmd2.go
8-rw-r--r-- 1 root root 519 Aug 19 21:38 http.go
9-rw-r--r-- 1 root root 462 Aug 19 22:29 test.py
10--- stderr ---
代码二
1package main
2import (
3 "fmt"
4 "os/exec"
5)
6func Cmd(cmd string, shell bool) []byte {
7if shell {
8 out, err := exec.Command("bash", "-c", cmd).Output()
9 if err != nil {
10 panic("some error found")
11 }
12 return out
13} else {
14 out, err := exec.Command(cmd).Output()
15 if err != nil {
16 panic("some error found")
17 }
18 return out
19 }
20}
21func main() {
22 //cmd := "ls -al"
23 cmd := "python test.py"
24 //cmd := "python -V" //没有输出
25 //cmd := "env"
26 out := string(Cmd(cmd,true))
27 //out := string(Cmd(cmd,false))
28 fmt.Println(out)
29}
因为都是调用的exec.Command方法并调用bash shell,本质上并没有什么区别。其也可以正常调用python脚本,但在直接调用python -V命令时没有输出,这点感觉很奇怪。
windows下执行命令的方法
1package main
2import(
3 "fmt"
4 "os/exec"
5)
6func main(){
7 c := exec.Command("cmd", "/C", "del", "D:\\a.txt")
8 if err := c.Run(); err != nil {
9 fmt.Println("Error: ", err)
10 }
11}
捐赠本站(Donate)
如您感觉文章有用,可扫码捐赠本站!(If the article useful, you can scan the QR code to donate))
- Author: shisekong
- Link: https://blog.361way.com/golang-command/5796.html
- License: This work is under a 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议. Kindly fulfill the requirements of the aforementioned License when adapting or creating a derivative of this work.