赞
踩
- func main() {
- cmd := exec.Command("ls", "-lah")
- out, err := cmd.CombinedOutput()
- if err != nil {
- log.Fatalf("cmd.Run() failed with %s\n", err)
- }
- fmt.Printf("combined out:\n%s\n", string(out))
-
-
- //比如我现在有个定时任务需要执行,封装一个方法自动执行
- cmdStr := "cd /go/leyangjun/test/ && ./main crontab --run=single --job=myCrontabName"
- runCmd := exec.Command("/bin/bash", "-c", cmdStr)
- runCmdOut, err := runCmd.CombinedOutput()
- if err != nil {
- fmt.Println("命令执行失败")
- }else{
-
- fmt.Println("命令执行成功")
- }
-
- }
-
-
-
- //检查命令是否存在
- func checkExists() {
- path, err := exec.LookPath("pwd")
- if err != nil {
- fmt.Printf("pwd不存在\n")
- } else {
- fmt.Printf("'pwd' executable is in '%s'\n", path)
- }
- }
-
-
- //两个命令依次执行
- func successivelyExists() {
- c1 := exec.Command("ls")
- c2 := exec.Command("wc", "-l")
- c2.Stdin, _ = c1.StdoutPipe()
- c2.Stdout = os.Stdout
- _ = c2.Start()
- _ = c1.Run()
- _ = c2.Wait()
- }
-
-
- //按行读取输出的内容
- func readByRowExists() {
- cmd := exec.Command("ls", "-h")
- stdout, _ := cmd.StdoutPipe()
- cmd.Start()
- reader := bufio.NewReader(stdout)
- for {
- line, err := reader.ReadString('\n')
- line = strings.TrimSpace(line)
- if err != nil || io.EOF == err {
- break
- }
- log.Println(line)
- }
- cmd.Wait()
- }
-
-
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。