Python - getting duration of a video with ffprobe

9.9k views Asked by At

I am new in Python and I am trying to get the duration (in seconds) of a file video by using ffprobe. Calling the following instruction

ffprobe -i video.mp4 -show_entries format=duration -v quiet -of csv="p=0"

on the CMD, I get the right result in seconds but if I call the same instruction in python by using:

import subprocess
duration = subprocess.call(['ffprobe', '-i', 'video.mp4', '-show_entries', 'format=duration', '-v', 'quiet', '-of', 'csv="p=0"'])
print duration

it returns 1. Is there a way to get the right result also through Python? Thank you in advance.

2

There are 2 answers

0
Pruthvi Raj On

The problem is with the double quote argument p=0 , format it using %, also i changed subprocess.call to subprocess.check_output to store output of the command in a string :

import subprocess
duration = subprocess.check_output(['ffprobe', '-i', 'video.mp4', '-show_entries', 'format=duration', '-v', 'quiet', '-of', 'csv=%s' % ("p=0")])
print(duration)

Output:

8.824000

or you can otherwise do this:

import subprocess
result = subprocess.Popen(["ffprobe", "video.mp4"],stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
for x in result.stdout.readlines():
      if "Duration" in x:
          print(x[12:23])
          break
2
DeWil On
from subprocess import check_output

file_name = "movie.mp4"

#For Windows
a = str(check_output('ffprobe -i  "'+file_name+'" 2>&1 |findstr "Duration"',shell=True)) 

#For Linux
#a = str(check_output('ffprobe -i  "'+file_name+'" 2>&1 |grep "Duration"',shell=True)) 

a = a.split(",")[0].split("Duration:")[1].strip()

h, m, s = a.split(':')
duration = int(h) * 3600 + int(m) * 60 + float(s)

print(duration)