在 python 中结束线程(也使用回调)

Ending a Thread in python (also using callbacks)

我在使用语音识别软件时发现了一种让语音识别器无限期收听的方法,从而提供更流畅的用户体验。我有一个 kickout 命令,如果曾经说过终止这个词,它应该结束程序。代码如下所示...

import speech_recognition as sr
import sys

def callback(recognizer, audio):                          # this is called from the background thread
    try:
        print("You said " + recognizer.recognize_google(audio))
        if(text == 'Terminate' or  text == 'terminate'):
             sys.exit()
    except:
        pass
r = sr.Recognizer()
r.listen_in_background(sr.Microphone(), callback)
import time
while True: time.sleep(0.1) 

我尝试将所有线程设置为守护进程并尝试使用 Os.exit()。如果还有其他我应该尝试的事情,请告诉我。

免责声明:这是未经测试的。我没有安装这个包。

然而,通过阅读 https://github.com/Uberi/speech_recognition/blob/master/speech_recognition/__init__.py 的源代码,我发现了这一点:

调用 listen_in_background return 是对 stopper() 函数的引用,它以可接受的良好方式终止侦听线程。为了利用这一点,请尝试以下操作:

import time
import speech_recognition as sr
import sys

stop_it = False

def callback(recognizer, audio):  # this is called from the background thread
    global stop_it
    try:
        print("You said " + recognizer.recognize_google(audio))
        if text.lower() == 'terminate':
            stop_it = True
    except:
        pass

r = sr.Recognizer()
just_try_and_stop_me = r.listen_in_background(sr.Microphone(), callback)

while True:
    if stop_it:
        just_try_and_stop_me(wait_for_stop=True)
        break
    time.sleep(0.1)

注意: 全局变量有点骇人听闻,因此对于您的下一个挑战,请尝试将所有这些封装在适当的 class 中。但就目前而言,这对初学者来说应该是相当不错的。此外,您的条件不需要括号(这不是 C)。此外,字符串上的 .lower() 方法将 return 小写版本以进行更简单的不区分大小写的比较。