You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

开发Spotify语音助手时遭遇KeyError: 'clientID'问题求助

Spotify语音助手KeyError: 'clientID'问题解决

问题描述

我正在开发一款Spotify语音助手,编写了两个.py文件:一个封装了获取URI、播放曲目等功能;另一个用于通过Spotify开发者平台创建应用获取的Client ID、Client Secret、Scope完成授权,同时已配置设备名称和重定向URI。但运行主文件时抛出KeyError: 'clientID'错误,相关代码及错误栈如下:

主文件代码

import pandas as pd
from speech_recognition import Microphone, Recognizer, UnknownValueError
import spotipy as sp
from spotipy.oauth2 import SpotifyOAuth

from Spots import spotsFunctions as sf, InvalidSearchError


# Set variables from setup.txt
setup = pd.read_csv('userDetails.txt', sep='=', index_col=0, header=None).squeeze()
clientID = setup['clientID']
clientSecret = setup['clientSecret']
deviceName = setup['deviceName']
redirectUri = setup['redirectUri']
scope = setup['scope']
username = setup['username']

# Connecting to the Spotify account
auth_manager = SpotifyOAuth(
    client_id = clientID,
    client_secret=clientSecret,
    redirect_uri=redirectUri,
    scope=scope,
    username=username)
spotify = sp.Spotify(auth_manager=auth_manager)

错误信息

File "D:\Spotify Voice Assistant\venv\lib\site-packages\pandas\core\indexes\base.py", line 3800, in get_loc
    return self._engine.get_loc(casted_key)
  File "pandas\_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\index.pyx", line 165, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\hashtable_class_helper.pxi", line 5745, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas\_libs\hashtable_class_helper.pxi", line 5753, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'clientID'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "D:\Spotify Voice Assistant\main.py", line 11, in <module>
    clientID = setup['clientID']
  File "D:\Spotify Voice Assistant\venv\lib\site-packages\pandas\core\series.py", line 982, in __getitem__
    return self._get_value(key)
  File "D:\Spotify Voice Assistant\venv\lib\site-packages\pandas\core\series.py", line 1092, in _get_value
    loc = self.index.get_loc(label)
  File "D:\Spotify Voice Assistant\venv\lib\site-packages\pandas\core\indexes\base.py", line 3802, in get_loc
    raise KeyError(key) from err
KeyError: 'clientID'

解决方案

1. 检查配置文件格式

你的代码通过pd.read_csv以=为分隔符读取userDetails.txt,要求文件必须是无表头、每行一个键值对的格式,示例如下:

clientID=你的Spotify客户端ID
clientSecret=你的Spotify客户端密钥
deviceName=你的播放设备名称
redirectUri=https://example.com/callback
scope=user-read-playback-state user-modify-playback-state playlist-read-private
username=你的Spotify用户名
  • 键名必须和代码中的clientID、clientSecret完全一致,大小写敏感
  • 键和值之间不能有多余空格,比如clientID = xxx会导致索引变为'clientID '(带空格),无法匹配代码中的'clientID'

2. 验证配置读取结果

在代码中添加调试代码,确认读取到的配置键是否正确:

setup = pd.read_csv('userDetails.txt', sep='=', index_col=0, header=None).squeeze()
print("配置文件中的所有键:", setup.index.tolist())

运行后如果输出里没有'clientID',说明配置文件的键名或格式有误。

3. 确认文件路径正确性

确保userDetails.txt和main.py在同一目录下。如果不在,需要使用完整路径读取,比如:

setup = pd.read_csv('D:/Spotify Voice Assistant/userDetails.txt', sep='=', index_col=0, header=None).squeeze()

4. 改用更稳定的配置读取方式

如果pandas的CSV读取方式容易出问题,可以用Python内置的文件解析逻辑,容错性更高:

config = {}
with open('userDetails.txt', 'r', encoding='utf-8') as f:
    for line in f:
        line = line.strip()
        # 跳过空行和注释
        if not line or line.startswith('#'):
            continue
        if '=' in line:
            key, value = line.split('=', 1)
            config[key.strip()] = value.strip()

# 从config字典中取值
clientID = config['clientID']
clientSecret = config['clientSecret']
deviceName = config['deviceName']
redirectUri = config['redirectUri']
scope = config['scope']
username = config['username']

内容的提问来源于stack exchange,提问作者Taha Habib

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 01:35:28