func runCmdInternal(dir string, cmd []string) error { exec := exec.Command(cmd[0], cmd[1:]...) exec.Dir = dir exec.Stdin = os.Stdin exec.Stdout = os.Stdout exec.Stderr = os.Stderr err := exec.Run() return err }
// execution helper func execCmd(cmd string) bool { log.Println("Exec:", cmd) exec := exec.Command(strings.Fields(cmd)[0], strings.Fields(cmd)[1:]...) err := exec.Run() if err != nil { return false } return true }
func TestInvalidArg() { // stdin, stdout, stderr c := "gich" + exeExt cmd, err := exec.Run(c, []string{c, "ZZZ"}, nil, "", exec.DevNull, exec.Pipe, exec.DevNull) if err != nil { panic("InvalidArg: " + err.String()) } buf, err := ioutil.ReadAll(cmd.Stdout) if err != nil { panic("InvalidArg read:" + err.String()) } if string(buf) != "" { panic("InvalidArg helpMsg: got " + string(buf)) } if err = cmd.Close(); err != nil { panic("InvalidArg close: " + err.String()) } }
func TestNoArgs() { // stdin, stdout, stderr c := "gich" + exeExt cmd, err := exec.Run(c, []string{c}, nil, "", exec.DevNull, exec.Pipe, exec.DevNull) if err != nil { panic("NoArgs: " + err.String()) } buf, err := ioutil.ReadAll(cmd.Stdout) if err != nil { panic("NoArgs read:" + err.String()) } if string(buf) != helpMsg { panic("NoArgs helpMsg: got " + string(buf)) } if err = cmd.Close(); err != nil { panic("NoArgs close: " + err.String()) } }
func TestFlagHelp() { // stdin, stdout, stderr c := "./gich" + exeExt cmd, err := exec.Run(c, []string{c, "-help"}, nil, "", exec.DevNull, exec.Pipe, exec.DevNull) if err != nil { panic("-help: " + err.String()) } buf, err := ioutil.ReadAll(cmd.Stdout) if err != nil { panic("-help read:" + err.String()) } if string(buf) != helpMsg { panic("-help helpMsg: got " + string(buf)) } if err = cmd.Close(); err != nil { panic("-help close: " + err.String()) } }
func TestMisc() { // stdin, stdout, stderr c := "gich" + exeExt cmd, err := exec.Run(c, []string{c, "cat"}, nil, "", exec.DevNull, exec.Pipe, exec.DevNull) if err != nil { panic("TestMisc: " + err.String()) } buf, err := ioutil.ReadAll(cmd.Stdout) if err != nil { panic("TestMisc read:" + err.String()) } if string(buf) != "/bin/cat\n" { panic("TestMisc cat: got " + string(buf)) } if err = cmd.Close(); err != nil { panic("-s close: " + err.String()) } }
func TestFlagS1() { // stdin, stdout, stderr c := "gich" + exeExt cmd, err := exec.Run(c, []string{c, "-s", "invalid_arg"}, nil, "", exec.DevNull, exec.Pipe, exec.DevNull) if err != nil { panic("-s: " + err.String()) } buf, err := ioutil.ReadAll(cmd.Stdout) if err != nil { panic("-s read:" + err.String()) } if string(buf) != "None\n" { panic("-s : got " + string(buf)) } if err = cmd.Close(); err != nil { panic("-s close: " + err.String()) } }
func main() { if cmd, e := exec.Run("/bin/ls", nil, nil, exec.DevNull, exec.Pipe, exec.MergeWithStdout); e == nil { b, _ := ioutil.ReadAll(cmd.Stdout) println("output: " + string(b)) } }