The golang execution command gets the status of the execution results

  • 2020-09-28 08:55:17
  • OfStack

These days I'm writing a tool with golang to execute the external command tool and also to output the log output of the external command tool. The Internet to find 1, a lot of information, the key is to execute the results of success or failure state did not find a good way to get to.

The first thing you want to do is look at the error log, and if there is an error log, then the execution fails. The test found that this did not work, found that some times will use error output log, but not 1 is the execution failure. Later, I tried to match with the keywords in the log, because some commands were executed successfully or failed with keyword output, and the test found that it was not very good.

In the end, I couldn't help it. I looked at it one time Cmd.Wait() The realization of the method, suddenly 1 light up, found the method, there is 1 Cmd.ProcessState The structure can be used. So I sorted out 1 and pasted 1 code to realize:


func Exec(name string, args ...string) error {
 cmd := exec.Command(name, args...)
 stderr, _ := cmd.StderrPipe()
 stdout, _ := cmd.StdoutPipe()
 if err := cmd.Start(); err != nil {
 log.Println("exec the cmd ", name, " failed")
 return err
 }
 //  Normal log 
 logScan := bufio.NewScanner(stdout)
 go func() {
 for logScan.Scan() {
  log.Println(logScan.Text())
 }
 }()
 //  The error log 
 errBuf := bytes.NewBufferString("")
 scan := bufio.NewScanner(stderr)
 for scan.Scan() {
 s := scan.Text()
 log.Println("build error: ", s)
 errBuf.WriteString(s)
 errBuf.WriteString("\n")
 }
 //  Wait for the command to finish executing 
 cmd.Wait()
 if !cmd.ProcessState.Success() {
 //  Execution failed, error message returned 
 return errors.New(errBuf.String())
 }
 return nil
}

Note: The above code does not handle input, and it does not apply if the command to be executed requires input data.

conclusion


Related articles: