Go系統命令管道操作
go 執行系統命令時不能直接使用管道符 |
實現方法如下:
方法一(同步)
func sync() {
cmd1 := exec.Command("ls", ".")
cmd2 := exec.Command("grep", "go")
cmd2.Stdout = os.Stdout
in, _ := cmd2.StdinPipe()
cmd1.Stdout = in
cmd2.Start()
cmd1.Run()
in.Close()
cmd2.Wait()
}
方法二(非同步)
func async() {
cmd1 := exec.Command("ls", ".")
cmd2 := exec.Command("grep", "go")
cmd2.Stdout = os.Stdout
out, _ := cmd1.StdoutPipe()
in, _ := cmd2.StdinPipe()
go func() {
defer func() {
out.Close()
in.Close()
}()
io.Copy(in, out)
}()
cmd1.Run()
cmd2.Run()
}
方法三(串聯)
func main() {
cmd1 := exec.Command("ls", ".")
cmd2 := exec.Command("grep", "go")
cmd3 := exec.Command("grep", "main")
cmd3.Stdout = os.Stdout
pipe(cmd1, cmd2, cmd3)
cmd1.Run()
cmd2.Run()
cmd3.Run()
}
func pipe(cmds ...*exec.Cmd) {
for i, cmd := range cmds {
if i > 0 {
out, _ := cmds[i-1].StdoutPipe()
in, _ := cmd.StdinPipe()
go func() {
defer func() {
out.Close()
in.Close()
}()
io.Copy(in, out)
}()
}
}
}
歡迎各位同學學習交流。
本作品採用《CC 協議》,轉載必須註明作者和本文連結