Problem: Delayed Output Display
Currently, your code processes a command and only displays its output once the execution is complete. You seek a solution to stream the output live instead of waiting for the process to finish.
Solution: Command Output Streaming
Employ the following approach to stream command output:
cmdParams := [][]string{ {filepath.Join(dir, path), "npm", "install"}, {filepath.Join(pdir, n.path), "gulp"}, } for _, cp := range cmdParams { log.Printf("Starting %s in folder %s...", cp[1:], cp[0]) cmd := exec.Command(cp[1], cp[2:]...) cmd.Dir = cp[0] stdout, err := cmd.StdoutPipe() if err != nil { log.Printf("%s cmd.StdoutPipe() error: %v\n", cp[1:], err) return } // Start command: if err = cmd.Start(); err != nil { log.Printf("%s start error: %v\n", cp[1:], err) return } // Stream command output: scanner := bufio.NewScanner(stdout) scanner.Split(bufio.ScanRunes) for scanner.Scan() { fmt.Print(scanner.Text()) } if scanner.Err() != nil { log.Printf("Reading %s stdout error: %v\n", cp[1:], err) return } // Get execution success or failure: if err = cmd.Wait(); err != nil { log.Printf("Error running %s: %v\n", cp[1:], err) return } log.Printf("Finished %s", cp[1:]) }
Explanation
The above is the detailed content of How to Stream Command Output in Real-time Instead of Waiting for Execution Completion?. For more information, please follow other related articles on the PHP Chinese website!