|exec.Command()
func Demo() (err error) {
psCmd := exec.Command("ps", "aux")
psStdout, psStderr := SetCommandStd(psCmd)
err = psCmd.Run()
if err != nil {
err = errors.New(err.Error() + psStderr.String())
return
}
// 筛选
grepCmd := exec.Command("grep", "mysql")
grepCmd.Stdin = psStdout
grepStdout, grepStderr := SetCommandStd(grepCmd)
err = grepCmd.Run()
if err != nil {
err = errors.New(err.Error() + grepStderr.String())
return
}
}
func SetCommandStd(cmd *exec.Cmd) (stdout, stderr *bytes.Buffer) {
stdout = &bytes.Buffer{}
stderr = &bytes.Buffer{}
cmd.Stdout = stdout
cmd.Stderr = stderr
return
}
楼下回答有正解