Search code examples
pythonloopstimerspotipy

Execute Python file every few seconds without time loop


I'm still a beginner and wrote some code to pull the currently playing track from the Spotify API. This works fine when I execute it once, but I want it to constantly update. I found a solution to execute a function every n seconds but this only prints the track that I first played. Even after the changing the song it still prints the song I played before.

The code I tried:

import spotipy
from spotipy.oauth2 import SpotifyOAuth
import cred
import time


scope = "user-read-playback-state"

sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=cred.client_id, client_secret=cred.client_secret, redirect_uri=cred.redirect_url, scope=scope, open_browser=False))

results = sp.current_user_playing_track()
starttime = time.time()

while True:
    print (results["item"]["name"])
    print (results["item"]["artists"][0]["name"])
    time.sleep(5.0 - ((time.time() - starttime) % 5.0))

Solution

  • I think your problem is that results is not updated inside the while loop.

    So simply move the while True: statement above results = sp.current_user_playing_track() so that the info is actually udpated each loop.