我想在Python中與主程序並行運行一個函數。假設我有語音識別功能。我希望它能夠在後臺運行,並且在聽到特定話語時中斷主程序。但同時,我還有其他任務要執行。所以,語音識別應該作爲一個單獨的過程來工作,並且可以在聽到命令時調用一個函數。在Python中並行運行函數
我試過蟒蛇多處理模塊,該線程模塊和線程模塊。但所有這些都要求我等待進程或線程完成。我想要的是可以讓我在後臺運行功能的東西。如果發生特定事件,他們必須調用一些回調函數。
我希望我會找到一個這樣做的有效方法。我試過線程模塊。代碼看起來像這樣(僞代碼):
def detected(text):
commands = 'a list of commands'
if text in commands:
#call some function according to the command
def speech_recognition():
#while True:
#If speech detected:
#record it
#process it and covert it to text
#if text is a specified command:
#call the detected(text) function with the recognized text as argument
import threading as t
pr = t.Thread(target=speech_recognition)
pr.start()
#from here starts the main program that does some other functions that
#doesn't need to be mentioned here.
但這不起作用。語音識別運行幾秒鐘,然後退出。沒有異常提出,沒有系統退出,什麼也沒有。當我嘗試多處理和線程模塊時,它是相同的。
這是什麼意思線程模塊需要你等到線程完成?如果你在一個線程上調用'join()',你只需要等待,但如果你不這樣做,你仍然可以在主線程中做其他的事情。 –
我編輯了這篇文章。看一看。 – freeMinder