Get Video-Duration with avconv via Python

送分小仙女□ 提交于 2019-12-13 04:39:11

问题


I need to get the duration of an Video for an application for Django. So I'll have to do this in python. But I'm really a beginner in this. So it would be nice, if you can help.

This is what I got so far:

import subprocess
task = subprocess.Popen("avconv -i video.mp4 2>&1 | grep Duration | cut -d ' ' -f 4 | sed -r 's/([^\.]*)\..*/\1/'", shell=True, stdout=subprocess.PIPE)
time = task.communicate()[0]
print time

I want to solve it with avconv because I'm allready using this at another point. The shell-command works well so far and gives me an output like: HH:MM:SS.

But when I'm executing the python-code I just get an non-interpretable symbol on the shell.

Thanks a lot allready for your help!

Found a solution. Problem was the sed-part:

import os
import subprocess

task = subprocess.Popen("avconv -i video.mp4 2>&1 | grep Duration | cut -d ' ' -f 4 | sed -e 's/.\{4\}$//'", shell=True, stdout=subprocess.PIPE)
time = task.communicate()[0]
print time

Because it is allways the same part, it was enought to just cut the last 4 characters.


回答1:


From python documentation:

Warning

Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.

So you should really user communicate for that:

import subprocess
task = subprocess.Popen("avconv -i video.mp4 2>&1 | grep Duration | cut -d ' ' -f 4 | sed -r 's/([^\.]*)\..*/\1/'", shell=True, stdout=subprocess.PIPE)
time = task.communicate()[0]
print time

That way you can also catch stderr message, if any.



来源:https://stackoverflow.com/questions/32294988/get-video-duration-with-avconv-via-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!