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
JavaScript
x
9
1
def logica_thread ( comand):
2
threading.Thread(target= logica ,args = (comand,), daemon = True).start()
3
4
def logica(comando):
5
request = requests.get('http://127.0.0.1:5000/' + comand)
6
time.sleep(5)
7
songs = request.json()['data']
8
return songs
9
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.
JavaScript
1
20
20
1
import threading
2
import time
3
4
5
def test_thread(list):
6
7
for i in range(10):
8
list.append(str(i))
9
10
11
my_list = []
12
13
my_thread = threading.Thread(target=test_thread, args=[my_list])
14
my_thread.start()
15
16
while my_thread.is_alive():
17
time.sleep(0.1)
18
19
print(my_list)
20
Result
JavaScript
1
2
1
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
2