Abdellah Benhammou
Abdellah Benhammou

Reputation: 412

using os.popen3() to extract thumbnail for a video in python

I am using ffmpeg to extract a frame from a video. This works fine when I use ffmpeg from the command line, however, when I try to do the same thing using the python:

os.popen3('ffmpeg -i videoPath -an -ss 00:00:02 -an -r 1 -vframes 1 -y picturePath')

I have no idea on how to get the extracted image. So far, I get only text saying (ffmpeg version N-62039-gc00f368 Copyright (c) 2000....) which is what I see in the command line. Would you please guide through what I need to do to get the image extracted. Thank you.

Upvotes: 0

Views: 589

Answers (2)

Simon Steinberger
Simon Steinberger

Reputation: 6825

I typically use the following function for that sort of tasks. It includes a timeout parameter for automatically aborting excessively long running processes. That's often handy when it comes to user uploaded content:

import subprocess
from threading import Timer

def run_with_timeout(cmd, sec):
    def kill_proc(p, killed):
        killed['val'] = True
        p.kill()
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    killed = {'val': False}
    timer = Timer(sec, kill_proc, [p, killed])
    timer.start()
    stdout, stderr = p.communicate()
    timer.cancel()
    return p.returncode, stdout, stderr, killed['val']

With that, you can simply call any shell command with options, which is run synchronously. That means the function waits until the process is finished. Therefore, when the function is done, the thumbnail is either created or an error is returned:

videoPath = '/path/to/video/source/file.mp4'
picturePath = '/path/to/output.jpg'
result = run_with_timeout(['ffmpeg', '-i', videoPath, '-an', '00:00:02', '-r', '1', '-vframes', '1', '-y', picturePath], 30)
if result[0] != 0:
    print 'error'
else:
    print 'success'
    # do something with videoPath 

Works in current Python versions 2.7.x.

Upvotes: 1

Python Novice
Python Novice

Reputation: 2200

os is deprecated. You should use subprocess.

Upvotes: 0

Related Questions