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

时间:2017-11-06 13:31:04

标签: python ffmpeg

我试图通过从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日志以及我得到的错误:

ffmpeg version 3.4 Copyright (c) 2000-2017 the FFmpeg developers
  built with Apple LLVM version 9.0.0 (clang-900.0.37)
  configuration: --prefix=/usr/local/Cellar/ffmpeg/3.4 --enable-shared --enable-pthreads --enable-version3 --enable-hardcoded-tables --enable-avresample --cc=clang --host-cflags= --host-ldflags= --enable-gpl --enable-libmp3lame --enable-libx264 --enable-libxvid --enable-opencl --enable-videotoolbox --disable-lzma
  libavutil      55. 78.100 / 55. 78.100
  libavcodec     57.107.100 / 57.107.100
  libavformat    57. 83.100 / 57. 83.100
  libavdevice    57. 10.100 / 57. 10.100
  libavfilter     6.107.100 /  6.107.100
  libavresample   3.  7.  0 /  3.  7.  0
  libswscale      4.  8.100 /  4.  8.100
  libswresample   2.  9.100 /  2.  9.100
  libpostproc    54.  7.100 / 54.  7.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'path_to_media_file':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf57.83.100
  Duration: 00:22:25.89, start: 0.000000, bitrate: 6059 kb/s
    Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1920x1080, 6057 kb/s, 15 fps, 30 tbr, 90k tbn, 180k tbc (default)
    Metadata:
      handler_name    : VideoHandler
[NULL @ 0x7fedac802200] Unable to find a suitable output format for '2>&1 | grep "Duration"'
2>&1 | grep "Duration": Invalid argument

2 个答案:

答案 0 :(得分:3)

您可以尝试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'])

返回:

1483.081723

答案 1 :(得分:2)

2>&1 | grep Duration是一个shell重定向。你只能将它与shell一起使用。

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

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

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

ffmpeg_get_mediafile_length = [
  'sh', '-c', 'ffmpeg -i "$1" 2>&1 | grep Duration',
  '_', test_file
]