通过Python使用avconv获取视频持续时间 [英] Get Video-Duration with avconv via Python
问题描述
我需要获取Django应用程序的视频时长。因此,我将不得不在python中执行此操作。但是我真的是一个初学者。
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
我想用avconv解决它,因为我已经准备好在另一点使用它了。到目前为止,shell命令运行良好,并提供如下输出:
HH:MM:SS。
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.
但是当我执行python代码时我只是在外壳上得到了一个不可解释的符号。
But when I'm executing the python-code I just get an non-interpretable symbol on the shell.
非常感谢您的帮助!
找到了解决方案。问题是sed部分:
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
因为总是相同的部分,所以只剪掉最后4个字符就足够了。
Because it is allways the same part, it was enought to just cut the last 4 characters.
推荐答案
从python文档中获取:
From python documentation:
警告
Warning
使用 communicate()
而不是 .stdin.write
, .stdout.read
或 .stderr.read
避免由于其他任何OS管道缓冲区填充和阻塞子进程而导致死锁。
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
这样,您还可以捕获stderr消息(如果有)。
That way you can also catch stderr message, if any.
这篇关于通过Python使用avconv获取视频持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!