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

Lew*_*wis 1 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)
Run Code Online (Sandbox Code Playgroud)

匹配变量打印出来:

b"{'minutes': b'04', 'hours': b'00', 'seconds': b'24.94'}"
Run Code Online (Sandbox Code Playgroud)

因此,所有输出在其开头都带有'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
Run Code Online (Sandbox Code Playgroud)

Jim*_*ard 8

看来你有一个byte对象.为了使用它,您可以执行以下操作**:

解码它:

matches = matches.decode("utf-8")
Run Code Online (Sandbox Code Playgroud)

然后,通过使用ast.literal_eval,翻译str到它真正的东西,a dict:

matches = ast.literal_eval(matches)
Run Code Online (Sandbox Code Playgroud)

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

int(matches['hours']) # returns 0
Run Code Online (Sandbox Code Playgroud)

**当然,这只是修复了一个真正不应该在这里的错误,正如@Tim指出的那样.


Tim*_*ker 5

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

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

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

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

应该做的(虽然我不确定如何使用stdout作为输入 ...)