gpt4 book ai didi

python - 从 ffmpeg 获取实时输出以在进度条中使用(PyQt4,stdout)

转载 作者:行者123 更新时间:2023-12-04 23:03:59 33 4
gpt4 key购买 nike

我已经查看了许多问题,但仍然无法弄清楚这一点。我正在使用 PyQt,并希望运行 ffmpeg -i file.mp4 file.avi并在流式传输时获取输出,以便我可以创建一个进度条。

我看过这些问题:
Can ffmpeg show a progress bar?
catching stdout in realtime from subprocess

使用以下代码,我可以看到 rsync 命令的输出:

import subprocess, time, os, sys

cmd = "rsync -vaz -P source/ dest/"
p, line = True, 'start'


p = subprocess.Popen(cmd,
shell=True,
bufsize=64,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE)

for line in p.stdout:
print("OUTPUT>>> " + str(line.rstrip()))
p.stdout.flush()

但是当我将命令更改为 ffmpeg -i file.mp4 file.avi我没有收到任何输出。我猜这与标准输出/输出缓冲有关,但我不知道如何读取看起来像的行
frame=   51 fps= 27 q=31.0 Lsize=     769kB time=2.04 bitrate=3092.8kbits/s

我可以用它来计算进度。

有人可以向我展示如何将这些信息从 ffmpeg 获取到 python 的示例,无论是否使用 PyQt(如果可能)

编辑:
我最终选择了 jlp 的解决方案,我的代码如下所示:
#!/usr/bin/python
import pexpect

cmd = 'ffmpeg -i file.MTS file.avi'
thread = pexpect.spawn(cmd)
print "started %s" % cmd
cpl = thread.compile_pattern_list([
pexpect.EOF,
"frame= *\d+",
'(.+)'
])
while True:
i = thread.expect_list(cpl, timeout=None)
if i == 0: # EOF
print "the sub process exited"
break
elif i == 1:
frame_number = thread.match.group(0)
print frame_number
thread.close
elif i == 2:
#unknown_line = thread.match.group(0)
#print unknown_line
pass

这给出了这个输出:
started ffmpeg -i file.MTS file.avi
frame= 13
frame= 31
frame= 48
frame= 64
frame= 80
frame= 97
frame= 115
frame= 133
frame= 152
frame= 170
frame= 188
frame= 205
frame= 220
frame= 226
the sub process exited

完美的!

最佳答案

在这种捕获 ffmpeg 状态输出(发送到 STDERR)的特定情况下,这个 SO 问题为我解决了它:FFMPEG and Pythons subprocess

诀窍是添加 universal_newlines=Truesubprocess.Popen()调用,因为 ffmpeg 的输出实际上是无缓冲的,但带有换行符。

cmd = "ffmpeg -i in.mp4 -y out.avi"
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,universal_newlines=True)
for line in process.stdout:
print(line)

另请注意,在此代码示例中,STDERR 状态输出直接重定向到 subprocess.STDOUT

关于python - 从 ffmpeg 获取实时输出以在进度条中使用(PyQt4,stdout),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25982993/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com