Home >Backend Development >Golang >How to Retrieve Realtime Output from Shell Commands in Go?

How to Retrieve Realtime Output from Shell Commands in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-11 02:56:09262browse

How to Retrieve Realtime Output from Shell Commands in Go?

Retrieve Realtime Output from Shell Commands in Go

Problem:

You want to execute shell commands in Go that may take time and retrieve their real-time output to process and display as progress information.

Solution:

1. Use os/exec for Shell Command Execution:

Create a Command using exec.Command to execute the desired shell command.

2. Capture Standard Error (stderr) Output:

By default, diagnostic messages from shell commands are sent to stderr instead of stdout. Use cmd.StderrPipe() to capture the stderr stream.

3. Create a Scanner to Read Output:

Use bufio.NewScanner to create a scanner that reads the stderr stream. Split the scan into words using bufio.ScanWords to obtain individual output lines.

4. Process and Display Output:

Inside a loop, use the scanner.Scan() method to retrieve each output line. Process it to extract the desired information, such as the progress ratio. Then, display the processed output.

5. Example Code:

Here's an example code that demonstrates how to do this:

package main

import (
    "bufio"
    "fmt"
    "os/exec"
    "strings"
)

func main() {
    args := "-i test.mp4 -acodec copy -vcodec copy -f flv rtmp://aaa/bbb"
    cmd := exec.Command("ffmpeg", strings.Split(args, " ")...)

    stderr, _ := cmd.StderrPipe()
    cmd.Start()

    scanner := bufio.NewScanner(stderr)
    scanner.Split(bufio.ScanWords)
    for scanner.Scan() {
        m := scanner.Text()
        fmt.Println(m)
    }
    cmd.Wait()
}

By following these steps, you can retrieve the real-time output from shell commands and process it to display progress information or any other desired information.

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

Statement:
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