I am new in Python and I want to get the value from a thread. I call the function logica in a thread and that function returns a value I want to know how can I get the value songs because I will use it later in an iter. Comand is a string. I am using the library threading
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
Advertisement
Answer
In your setup that is a little difficult because you have no reference to the thread. So
- After starting it when is the thread ready?
- Where to are the results returned?
1 can be fixed by assigning the thread to a variable. 2 in your case you can provide an external list for the results and pass it as argument.
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)
Result
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']