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

使用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>
      
  • 禁用自动打开浏览器:初始化SpotifyOAuth时添加open_browser=False,运行后终端会输出授权链接,手动复制到浏览器完成授权即可,避免浏览器自动占用端口。

二、修正代码中的其他错误

你的代码还有几处逻辑和语法问题,不修正的话即使解决端口问题也会报错:

  1. 变量名不匹配:用search接收搜索结果,后续却用了未定义的result,需统一变量名。
  2. 搜索结果路径错误:Spotify搜索返回结构是tracks->items(均为复数),且uri是字符串键,必须加引号。
  3. 获取播放列表方法错误:user_playlist需要指定具体播放列表ID,应改用user_playlists(复数)获取所有列表;更高效的方式是创建播放列表后直接取返回的ID,无需后续查询。
  4. 未处理无搜索结果的情况:如果搜索不到歌曲会触发索引错误,建议添加判断逻辑。

修正后的完整代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 15:39:14