os/exec包可用于调用外部命令,可以使用管道连接输入输出,并支持阻塞与非阻塞方式执行命令。
os/exec包中关键的类型为Cmd,以下介绍的所有方法皆服务于该类型:
func Command(name string, arg ...string) *Cmdfunc (c *Cmd) Run() errorfunc (c *Cmd) Start() errorfunc (c *Cmd) Wait() errorfunc (c *Cmd) Output() ([]byte, error)func (c *Cmd) CombinedOutput() ([]byte, error)func (c *Cmd) StdinPipe() (io.WriteCloser, error)func (c *Cmd) StdoutPipe() (io.ReadCloser, error)func (c *Cmd) StderrPipe() (io.ReadCloser, error)
普通调用示例:
调用Shell命令或可执行文件
演示在当前目录创建一个空文件
package main
import (
"fmt"
"os/exec"
)
func main(){
cmd := exec.Command("touch", "test_file")
err := cmd.Run()
if err != nil {
fmt.Println("Execute Command failed:" + err.Error())
return
}
fmt.Println("Execute Command finished.")
}
cmd := exec.Command("my_shell.sh")#sh my_shell.sh
调用Shell脚本
dir_size.sh
package main
import (
"fmt"
"os/exec"
)
func main(){
command := `./dir_size.sh .`
cmd := exec.Command("/bin/bash", "-c", command)
output, err := cmd.Output()
if err != nil {
fmt.Printf("Execute Shell:%s failed with error:%s", command, err.Error())
return
}
fmt.Printf("Execute Shell:%s finished with output:\n%s", command, string(output))
}
dir_size.sh
#!/bin/bash
du -h --max-depth=1 $1
Go程序运行结果:
[root@localhost opt]# ll
total 2120
-rwx------. 1 root root 36 Jan 22 16:37 dir_size.sh
-rwx------. 1 root root 2152467 Jan 22 16:39 execCommand
drwxrwxr-x. 11 1000 1000 4096 Jul 12 2017 kibana
drwx------. 2 root root 4096 Jan 16 10:45 sftpuser
drwx------. 3 root root 4096 Jan 22 16:41 upload
[root@localhost opt]# ./execCommand
Execute Shell:./dir_size.sh . finished with output:
4.0K ./sftpuser
181M ./kibana
1.1G ./upload
1.2G .
使用输入输出Pipe
test
package main
import (
"fmt"
"io/ioutil"
"os/exec"
)
func main(){
cmd := exec.Command("/bin/bash", "-c", "grep test")
stdin, _ := cmd.StdinPipe()
stdout, _ := cmd.StdoutPipe()
if err := cmd.Start(); err != nil{
fmt.Println("Execute failed when Start:" + err.Error())
return
}
stdin.Write([]byte("go text for grep\n"))
stdin.Write([]byte("go test text for grep\n"))
stdin.Close()
out_bytes, _ := ioutil.ReadAll(stdout)
stdout.Close()
if err := cmd.Wait(); err != nil {
fmt.Println("Execute failed when Wait:" + err.Error())
return
}
fmt.Println("Execute finished:" + string(out_bytes))
}
Go程序运行结果:
[root@localhost ~]# ./execCommand
Execute finished:go test text for grep
阻塞/非阻塞方式调用
文章开头方法介绍处已经介绍的很清楚,且前面示例都有涉及,就不另行说明了。