使用Python的Spotipy库遇端口占用错误及重定向URI问题
解决Spotipy中OSError: [Errno 48] Address already in use及代码其他问题
一、处理“地址已占用”错误
这个错误是因为本地8888端口已被其他程序占用,三种解决方式任选其一:
- 更换未被占用的端口:把代码里的
redirect_uri改成http://localhost:8889/callback(或8000等其他端口),同时去Spotify开发者控制台的应用设置里,同步更新重定向URI为新地址。 - 杀掉占用8888端口的进程:
- Mac/Linux终端执行:
lsof -i :8888 # 获取占用端口的进程PID kill -9 <查到的PID> - Windows命令提示符执行:
netstat -ano | findstr :8888 # 获取进程PID taskkill /F /PID <查到的PID>
- Mac/Linux终端执行:
- 禁用自动打开浏览器:初始化
SpotifyOAuth时添加open_browser=False,运行后终端会输出授权链接,手动复制到浏览器完成授权即可,避免浏览器自动占用端口。
二、修正代码中的其他错误
你的代码还有几处逻辑和语法问题,不修正的话即使解决端口问题也会报错:
- 变量名不匹配:用
search接收搜索结果,后续却用了未定义的result,需统一变量名。 - 搜索结果路径错误:Spotify搜索返回结构是
tracks->items(均为复数),且uri是字符串键,必须加引号。 - 获取播放列表方法错误:
user_playlist需要指定具体播放列表ID,应改用user_playlists(复数)获取所有列表;更高效的方式是创建播放列表后直接取返回的ID,无需后续查询。 - 未处理无搜索结果的情况:如果搜索不到歌曲会触发索引错误,建议添加判断逻辑。
修正后的完整代码
import spotipy from spotipy.oauth2 import SpotifyOAuth def create_playlist(): client_id = '_______' client_secret = '______' redirect_uri = 'http://localhost:8889/callback' # 更换端口解决占用问题 username = 'csrupido01' scope = 'playlist-modify-public' # 可选:添加open_browser=False避免自动打开浏览器 token = SpotifyOAuth(scope=scope, username=username, client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri, open_browser=False) spotifyObject = spotipy.Spotify(auth_manager=token) playlist_name = input("Enter the name of the playlist: ") playlist_desc = input("Enter a description for the playlist: ") # 创建后直接获取播放列表ID,无需后续查询 created_playlist = spotifyObject.user_playlist_create( user=username, name=playlist_name, public=True, description=playlist_desc ) playlist_id = created_playlist['id'] song = input("Enter a song (type 'quit' to stop): ") song_uris = [] while song.lower() != "quit": search_result = spotifyObject.search(q=song, type='track', limit=1) tracks = search_result['tracks']['items'] if tracks: song_uri = tracks[0]['uri'] song_uris.append(song_uri) print(f"Added: {tracks[0]['name']} by {tracks[0]['artists'][0]['name']}") else: print(f"No results found for '{song}'") song = input("Enter another song (type 'quit' to stop): ") if song_uris: spotifyObject.user_playlist_add_tracks( user=username, playlist_id=playlist_id, tracks=song_uris ) print(f"Successfully added {len(song_uris)} songs to playlist '{playlist_name}'") else: print("No songs were added to the playlist.") create_playlist()
内容的提问来源于stack exchange,提问作者James Sparks
相关产品推荐
相关产品推荐

