如何设置计时器来控制循环内的函数调用?
Posted
技术标签:
【中文标题】如何设置计时器来控制循环内的函数调用?【英文标题】:How can I set a Timer to control a function call inside a loop? 【发布时间】:2016-08-27 17:42:17 【问题描述】:我有这个function
,它播放Spotify
:
#a function to play Spotify
def play(id_):
print 'playing', id_
os.system("osascript -e 'tell application \"Spotify\" to play track \"%s\"'" % (id_,))
以及下面的loop
,遍历所有playlist
的歌曲,获取所有可播放的id
的(foreign_id
),传递给play(id_)
,
然后将每首歌曲 duration
传递给 time.sleep()
以停止循环,直到每首歌曲完成,然后再次重复循环:
for i, song in enumerate(song_playlist):
#we need to track each song id
song_id = song_playlist[i]['id']
#in order to get song 'duration', access 'song/profile response' and pass the id as an argument
response_profile = en.get('song/profile', id=song_id, bucket="audio_summary")
song_profile = response_profile['songs']
dur = song_profile[0]['audio_summary']['duration']
#convert to miliseconds
dur *= 1000
print int(round(dur))
#now we access each song 'foreign_id'
for track in song:
track = song['tracks'][i]
track_id = track['foreign_id'].replace('-WW', '')
print '0 2 1'.format(i, song['artist_name'], song['title'])
#call the function for each track
play(track_id) #CALL FUNCTION HERE
time.sleep(int(round(dur))) # SET INTERVAL CALL TO EACH SONG DURATION
但是,只播放了一首歌曲,递归消失了。
如何更正代码,以便我可以让按顺序播放所有曲目的功能只运行一次代码?
【问题讨论】:
不能通过song_id = song['id']
获得song_id
【参考方案1】:
看起来play(track_id)
应该在for track in song
循环内。您需要将其缩进 1 级。
for i, song in enumerate(song_playlist):
# Code as before ...
for track in song:
track = song['tracks'][i]
track_id = track['foreign_id'].replace('-WW', '')
print '0 2 1'.format(i, song['artist_name'], song['title'])
play(track_id) #CALL FUNCTION HERE
time.sleep(int(round(dur))) # SET INTERVAL CALL TO EACH SONG DURATION
【讨论】:
以上是关于如何设置计时器来控制循环内的函数调用?的主要内容,如果未能解决你的问题,请参考以下文章
等到 for 循环内的所有函数调用结束其执行 - Javascript
在javascript中 setInterval()、clearInterval()、clearTimeout()等等常用的函数的含义是啥?