繁体   English   中英

python线程中的返回值

[英]Return value in a python thread

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

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']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM