这期内容当中小编将会给大家带来有关golang中怎么利用exec.Command执行带管道命令,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
使用 sh -c ""
命令
exec.Command("bash", "-c", "ps aux|grep go")
这是推荐的做法。
如果输出不是很多,推荐使用github.com/go-cmd/cmd
库来执行系统命令,如:
import "github.com/go-cmd/cmd"
c := cmd.NewCmd("bash", "-c", "ps aux|grep go")
<-c.Start()
fmt.Println(c.Status().Stdout)
使用io.Pipe()
连接两个命令
ps := exec.Command("ps", "aux")
grep := exec.Command("grep", "go")
r, w := io.Pipe() // 创建一个管道
defer r.Close()
defer w.Close()
ps.Stdout = w // ps向管道的一端写
grep.Stdin = r // grep从管道的一端读
var buffer bytes.Buffer
grep.Stdout = &buffer
ps.Start()
grep.Start()
ps.Wait()
w.Close()
grep.Wait()
io.Copy(os.Stdout, &buffer)
第二种方法非常不方便,而且无法使用grep.Stdout()
,grep.StdoutPipe()
获取输出
上述就是小编为大家分享的golang中怎么利用exec.Command执行带管道命令了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注天达云行业资讯频道。