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:
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.
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.
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.
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() }
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
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!