ffmpeg:使用脚本获取持续时间:无法为“2>&1”grep“duration”找到合适的输出格式

2024-04-26 07:34:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过从python脚本运行以下行来获取媒体文件的持续时间:

test_file = 'path_to_file.mp4'
ffmpeg_get_mediafile_length = ["ffmpeg", "-i", test_file, '2>&1 | grep "Duration"']
output = subprocess.Popen(ffmpeg_get_mediafile_length,
                        stdout = subprocess.PIPE
                        ).stdout.read()
print output # this gives None
matches = re_length.search(output)
print matches

下面是我得到的ffmpeg日志和我得到的错误:

^{pr2}$

Tags: pathtest脚本outputgetstdoutlengthffmpeg
2条回答

您可以尝试ffprobe,它可以输出JSON,并且不需要grep和regexp结果-但是返回的持续时间以秒为单位:

import shlex
import subprocess
import json    

filePath = '/home/f3k/Downloads/tr5.mp4'
command = shlex.split('/usr/bin/ffprobe -v quiet -print_format json -show_format -show_streams')
command.append(filePath)
proc = subprocess.Popen(command, stdout = subprocess.PIPE)
stdout, _ = proc.communicate()

output = json.loads(stdout)
print  (output['format']['duration'])

退货:

^{pr2}$

2>&1 | grep Duration是shell重定向。你只能用一个外壳。在

那么,最短的就是生成一个shell脚本并设置shell=True

ffmpeg_get_mediafile_length = 'ffmpeg -i %s 2>&1 | grep "Duration"' % (pipes.quote(test_file))

或者,不需要更改其他代码行:

^{pr2}$

相关问题 更多 >