Home > Backend Development > Golang > How to Stream Command Output in Go for Live Results?

How to Stream Command Output in Go for Live Results?

Mary-Kate Olsen
Release: 2024-11-20 13:32:17
Original
431 people have browsed it

How to Stream Command Output in Go for Live Results?

Streaming Command Output for Live Results

Executing commands in Go allows you to interact with external processes, but if you need the output in real-time, there's a way to achieve it.

In your code snippet, the output is printed all at once after the command has completed. To display the output live, you can incorporate the technique outlined below:

// ... Previous code

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:])
}

// ... Remaining code
Copy after login

Explanation

This modification uses a bufio.Scanner to read the standard output of the command in real-time. The Split(bufio.ScanRunes) instructs the scanner to read individual characters, which allows you to display the output as it's being generated.

By repeatedly calling scanner.Scan() and printing the scanner.Text() until the end of the output is reached, you can stream the command's output live on the screen.

The above is the detailed content of How to Stream Command Output in Go for Live Results?. 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