How to Stream Live Output from Executed Commands in Go?

Mary-Kate Olsen
Release: 2024-11-24 05:48:09
Original
725 people have browsed it

How to Stream Live Output from Executed Commands in Go?

Live Output of Executed Commands

This code snippet showcases a problem often encountered when running commands and retrieving their output in Go: the output becomes available only after the command has finished executing. To address this, a modified solution is provided that allows for live streaming of the command's 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:])
}
Copy after login

Explanation:

  • cmd.StdoutPipe() creates a pipe that allows us to read the command's standard output in real-time.
  • bufio.NewScanner(stdout) creates a scanner that reads from the output pipe by runes (characters).
  • scanner.Scan() reads and prints each character as it becomes available.
  • The loop continues reading and printing characters until the command finishes or an error occurs.
  • After the command finishes, the remaining output is printed, and the command's exit status is retrieved.

Additional Notes:

  • This solution only streams standard output. Standard error can also be streamed using Command.StderrPipe().
  • Some commands may not write everything to their standard output or error. In such cases, the output may not be streamed correctly.

The above is the detailed content of How to Stream Live Output from Executed Commands in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template