我想在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