My question is how to thread a function that needs time to execute , then return a value , whilst I can do other stuff at the same time.
I saw others similar questions and solutions but I don't get how to apply them here.
import speech_recognition as sr
r = sr.Recognizer()
import threading
from queue import Queue
queue = Queue()
def mySpeechRecognizer():
print("START SPEECH INPUT\n") #
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source)
try:
audio = r.listen(source)#, timeout = 5) #####
userInput = r.recognize_google(audio)
if any(userInput) == True:
print("Text Input :", userInput) #
# do sth here
print("END SPEECH INPUT NORMAL") #
return userInput #
except Exception as e:
print("Exception In Function mySpeechRecognizer() :", e)
print("END SPEECH INPUT EXCEPTION") #
return #
recognize = threading.Thread(target = lambda q: q.put(mySpeechRecognizer()), args = (queue, ))
recognize.start()
print('do sth')
recognize.join()
print('do sth')
print(queue.get())
print('do sth')
My expectation is that it will print 3 times "do sth" while recognizing. Once it finishes , it will print the return value without blocking the print , i.e. getting queue.get() while print
How can I accomplish this , and what's wrong with my attempt ?