我很新
所以这个 getLength 函数将在 python 2.7 中运行良好,但我无法让它在 3.10 中运行。想知道是否有人可以建议可能需要更改的内容,因为我不知所措。当我尝试打印退货时,那里什么都没有。我 95% 确定问题出在 result = subprocess.Popen() 行,但为了完整起见,我包含了整个函数
#function... 返回视频文件的持续时间 HH:MM:SS
def getLength(filename):
#uses ffprobe to get info about the video file
result = subprocess.Popen(["ffprobe", filename],
stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
#finds the info that has the word "Duration"
y = [x for x in result.stdout.readlines() if "Duration: " in x]
#get the location of the "Duration: " phrase
loc = y[0].find("Duration: ")
#assuming we find the location of that phrase..
if loc != -1:
#cut out everything before and everything more than 10 characters later
print ( y[0][loc+10:loc+18] )
return y[0][loc+10:loc+18]
else:
#if we don't find anything then set it to be 2 seconds of nothing...
print ( y[0][loc+10:loc+18] )
return '00:00:02'
最佳答案
在 Python 3 中,字符串位于 Unicode format , 和 stdout
输出是字节数组。
我们可以使用 x.decode("utf-8")
将字节数组转换为字符串。 :
解析列表可能如下所示:
y = [x.decode("utf-8") for x in result.stdout.readlines() if "Duration: " in x.decode("utf-8")]
完整的代码示例(使用
stderr
而不是 stdout
):import subprocess
def get_length(filename):
# Uses FFprobe to get info about the video file
result = subprocess.Popen(["ffprobe", filename], stderr=subprocess.PIPE)
# Finds the info that has the word "Duration"
# Convert bytes array to strings using decode("utf-8")
y = [x.decode("utf-8") for x in result.stderr.readlines() if "Duration: " in x.decode("utf-8")]
# Get the location of the "Duration: " phrase
loc = y[0].find("Duration: ")
# Assuming we find the location of that phrase..
if loc != -1:
# Cut out everything before and everything more than 10 characters later
print(y[0][loc+10:loc+18])
return y[0][loc+10:loc+18]
else:
# If we don't find anything then set it to be 2 seconds of nothing...
print(y[0][loc+10:loc+18])
return '00:00:02'
res = get_length('BBB.ogv')
print(res)
为了获取 OVG(或 MP4)文件的视频时长,我们可以选择 JSON 格式:
import subprocess as sp
import json
# https://superuser.com/questions/650291/how-to-get-video-duration-in-seconds
data = sp.run(["ffprobe", '-v', 'error', '-select_streams', 'v', '-of', 'default=noprint_wrappers=1:nokey=1', '-show_entries', 'stream=duration', '-of', 'json', 'BBB.ogv'], stdout=sp.PIPE).stdout
dict = json.loads(data)
print(dict['streams'][0]['duration'])
关于python-3.x - Python 3.10 中 ffprobe 的困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71137615/