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

How to Get Realtime Output from Shell Commands in Go?

Barbara Streisand
Release: 2024-12-08 18:51:15
Original
491 people have browsed it

How to Get Realtime Output from Shell Commands in Go?

How to Retrieve Realtime Output for Shell Commands in Go

Problem:

When executing a long-running shell command in Go using os/exec, how can you retrieve the real-time output and process it as it becomes available?

Solution:

  1. Use stderr Instead of stdout:

    ffmpeg is known to output diagnostic messages to stderr instead of stdout. Therefore, connect to stderr when creating the command object instead of stdout.

  2. Read Output from stderr Continuously:

    Create a bufio.Scanner for stderr and use the Scan method to read the output line by line or word by word.

  3. Handle Output Line by Line:

    In the example code, a scanner.Split(bufio.ScanWords) is used to split the output on spaces. Adjust the split type based on your processing requirements.

  4. Process Output:

    Manipulate the output in your desired manner, such as extracting and processing progress information.

Example Code:

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()
}
Copy after login

Output:

The code will continuously print the ffmpeg output messages, such as:

frame=  101 fps=0.0 q=28.0 size=      91kB time=00:00:04.13 bitrate= 181.2kbits/s
Copy after login

The above is the detailed content of How to Get Realtime Output from Shell 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