“TypeError:字节索引必须是整数或切片,而不是str”将字节转换为整数

时间:2015-11-18 07:08:35

标签: python ffmpeg

我正在使用其他程序(ffmpeg)来获取已下载的YouTube视频的长度,以便随机化视频中的特定点。但是,当我尝试执行此代码时,我收到此错误:

def grabTimeOfDownloadedYoutubeVideo(youtubeVideo):
    process = subprocess.Popen(['/usr/local/bin/ffmpeg', '-i', youtubeVideo], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    stdout, stderr = process.communicate()
    matches = str(re.search(b"Duration:\s{1}(?P<hours>\d+?):(?P<minutes>\d+?):(?P<seconds>\d+\.\d+?),", stdout, re.DOTALL).groupdict()).encode()
    print(matches)
    hours = int(matches['hours'])
    minutes = int(matches['minutes'])
    seconds = int(matches['seconds'])
    total = 0
    total += 60 * 60 * hours
    total += 60 * minutes
    total += seconds
    print(total)

匹配变量打印出来:

b"{'minutes': b'04', 'hours': b'00', 'seconds': b'24.94'}"

所以所有的输出在它的开头都带有'b'。如何删除“b”并获取号码?

此处有完整的错误消息:

Traceback (most recent call last):
  File "bot.py", line 87, in <module>
    grabTimeOfDownloadedYoutubeVideo("videos/1.mp4")
  File "bot.py", line 77, in grabTimeOfDownloadedYoutubeVideo
    hours = int(matches['hours'])
TypeError: byte indices must be integers or slices, not str

2 个答案:

答案 0 :(得分:7)

似乎你有一个byte对象。为了使用它,您可以执行以下操作**:

解码它:

matches = matches.decode("utf-8")

然后,使用 ast.literal_eval ,将str翻译成真实的,dict

matches = ast.literal_eval(matches)

然后您可以像往常一样访问匹配内容:

int(matches['hours']) # returns 0

**当然,这只是修复了一个错误,这个错误在@Tim指出的时候不应该首先出现在这里。

答案 1 :(得分:5)

matches = str(re.search(b"Duration:\s{1}(?P<hours>\d+?):(?P<minutes>\d+?):(?P<seconds>\d+\.\d+?),", stdout, re.DOTALL).groupdict()).encode()

很奇怪。通过将正则表达式匹配的结果转换为字符串,您将导致错误(因为现在matches['hours']将失败)。

通过将该字符串编码为bytes对象(为什么?),您将进一步复杂化。

matches = re.search(r"Duration:\s(?P<hours>\d+?):(?P<minutes>\d+?):(?P<seconds>\d+\.\d+?),", stdout).groupdict()

应该这样做(虽然我不确定将stdout用作输入 ...)