Return 值在 python 线程中

Return value in a python thread

我是 Python 的新手,我想从线程中获取值。我在一个线程中调用函数 logica,该函数 returns 是一个值,我想知道如何获得值歌曲,因为稍后我将在 iter 中使用它。命令是一个字符串。我正在使用线程库

def logica_thread ( comand):
        threading.Thread(target= logica ,args = (comand,), daemon = True).start()       
 
def logica(comando):
    request = requests.get('http://127.0.0.1:5000/' + comand)
    time.sleep(5) 
    songs = request.json()['data']
    return songs

在您的设置中这有点困难,因为您没有引用线程。所以

  1. 启动后线程什么时候准备好?
  2. 结果返回到哪里?

1 可以通过将线程分配给变量来修复。 2 在您的情况下,您可以为结果提供一个外部列表并将其作为参数传递。

import threading
import time


def test_thread(list):

    for i in range(10):
        list.append(str(i))


my_list = []

my_thread = threading.Thread(target=test_thread, args=[my_list])
my_thread.start()

while my_thread.is_alive():
    time.sleep(0.1)

print(my_list)

结果

['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']