Skip to main content
 首页 » 编程设计

python之"TypeError: byte indices must be integers or slices, not str"将字节转换为整数

2025年05月04日10jackei

我正在使用不同的程序 (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) 

matches 变量打印如下:

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 

请您参考如下方法:

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

解码:

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

然后,通过使用 ast.literal_eval ,将 str 翻译成它真正的意思,dict:

matches = ast.literal_eval(matches) 

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

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

**当然,这只是修复了一个错误,正如@Tim 指出的那样,这个错误一开始就不应该出现在此处。