首页 > 解决方案 > 如何将线程中的值存储到数据框中,同时从所述数据框中提取值?

问题描述

所以我正在使用 spotify 的 api 来访问艺术家的音乐。我设法从艺术家列表中获取了一首歌曲,并将该歌曲存储到一个全局数据框变量中。现在,我想在后台运行线程,将新歌曲添加到全局数据框变量中,而数据框包含一定数量的歌曲。有没有办法在后台运行一个线程,将结果返回到全局数据帧中,同时在前台运行一个while循环来检查全局数据帧并根据用户输入对其进行修改?

线程在后台运行此方法,返回一首歌曲添加到全局变量

def find_recs(self):
        global recommended
        song = song_rec()
        print("song added to recommendations!")
        return song

检查推荐的长度。当采取行动时,第一行将从 df 中弹出

def recommend():
    rec = recommended
    while True:
        if(len(rec) > 2):
            rec.reset_index(drop=True, inplace=True)
            print("would you like to add \'" +
                rec['name'][0] + "\' by " + rec['artist'][0] + " to your playlist? y/n")
            answer = input()
            if answer == "y":
                sp.app.add_to_queue(rec['uri'][0])
                rec = rec.drop(0)
            elif answer == "n":
                rec = rec.drop(0)
            elif answer == "q":
                print('quitting program')
                stop_threads = False
                sys.exit()
            else:
                print("Choose a valid input")
                
        time.sleep(2)
        print('checking...')

标签: pythonpandasmultithreadingspotifymultitasking

解决方案


推荐阅读