我试图在golang中使用os / exec调用shell命令,该命令将花费一些时间,所以我想检索reatime输出并打印处理后的输出(进度比率数字).
package main import ( "bufio" "fmt" "io" "os" "os/exec" "strings" ) func main() { cmdName := "ffmpeg -i t.webm -acodec aac -vcodec libx264 cmd1.mp4" cmdArgs := strings.Fields(cmdName) cmd := exec.Command(cmdArgs[0],cmdArgs[1:len(cmdArgs)]...) stdout,_ := cmd.StdoutPipe() cmd.Start() go print(stdout) cmd.Wait() } // to print the processed information when stdout gets a new line func print(stdout io.ReadCloser) { r := bufio.NewReader(stdout) line,_,err := r.ReadLine() fmt.Println("line: %s err %s",line,err) }
我希望有一个功能可以在命令打印时更新屏幕,
ffmpeg命令输出如下:
frame= 101 fps=0.0 q=28.0 size= 91kB time=00:00:04.13 bitrate= 181.2kbits/ frame= 169 fps=168 q=28.0 size= 227kB time=00:00:06.82 bitrate= 272.6kbits/ frame= 231 fps=153 q=28.0 size= 348kB time=00:00:09.31 bitrate= 306.3kbits/ frame= 282 fps=140 q=28.0 size= 499kB time=00:00:11.33 bitrate= 360.8kbits/
事实上,上面的4行是ffmpeg命令输出的最后一行,它不断变化,我想打印出来的变化,就像
18% 44% 69% 100%
我怎么能实现这个目标?
看起来像ffmpeg发送所有诊断消息(“控制台输出”)
到stderr而不是stdout.下面的代码适合我.
到stderr而不是stdout.下面的代码适合我.
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() }
ffmpeg的版本详述如下.
ffmpeg version 3.0.2 Copyright (c) 2000-2016 the FFmpeg developers built with Apple LLVM version 7.3.0 (clang-703.0.29) configuration: --prefix=/usr/local/Cellar/ffmpeg/3.0.2 --enable-shared --enable-pthreads --enable-gpl --enable-version3 --enable-hardcoded-tables --enable-avresample --cc=clang --host-cflags= --host-ldflags= --enable-opencl --enable-libx264 --enable-libmp3lame --enable-libxvid --enable-vda libavutil 55. 17.103 / 55. 17.103 libavcodec 57. 24.102 / 57. 24.102 libavformat 57. 25.100 / 57. 25.100 libavdevice 57. 0.101 / 57. 0.101 libavfilter 6. 31.100 / 6. 31.100 libavresample 3. 0. 0 / 3. 0. 0 libswscale 4. 0.100 / 4. 0.100 libswresample 2. 0.101 / 2. 0.101 libpostproc 54. 0.100 / 54. 0.100