多线程尝试Python失败

时间:2017-07-31 16:16:14

标签: windows python-3.x python-multithreading

以下代码是我在语音识别程序中的尝试。语音识别工作正常,可以理解我,但我在程序中的某些点遇到问题,代码会冻结或挂起,但没有错误。

为了解决这个问题,我尝试使用多线程添加计时器,该计时器应从a = True开始,3秒后程序将自动关闭。如果识别工作完美,a = False应该在关闭程序之前停止计时器。这显然没有用,或者我不会在这里。

我在这里和那里添加了一些打印语句,所以我可以在视觉上看到代码在运行时的位置,并且我看到了计时器的代码开始,但是语音识别的代码没有。

import speech_recognition as sr
r = sr.Recognizer()
import os, threading, time, sys
import subprocess as sp

print("Voice Recognition Software\n\n***********************************\n")

class myThread (threading.Thread):
    def run():
        print("Checking")
        while True:
            if a == True:
                if a == False:
                    continue
                for x in range(3):
                    time.sleep(1)
                    if a == False:
                        break
                sys.exit()  
def program():
    while True:
        print("voice recog has begun")
        r.energy_threshold = 8000
        t = None
        with sr.Microphone() as source:

            print (">")
            a = True
            audio = r.listen(source)
            a = False
            try:
                a = True
                print("Processing...")
                t = r.recognize_google(audio)
                a = False
                print (": " + t)
            except sr.UnknownValueError:
                print("Unknown input")
                continue
            except sr.RequestError as e:
                print("An error occured at GAPI\nA common cause is lack of internet connection")
                continue

            if "open" in t:
                t = t.replace("open","")
                t = t.replace(" ","")
                t = t + ".exe"
                print (t)

                for a,d,f in os.walk("C:\\"):
                    for files in f:
                         if files == t.lower() or files == t.capitalize() or files == t.upper():
                            pat = os.path.join(a,files)
                            print (pat)
                            sp.call([pat])
                            success = True
            if success == True:
                continue

a = False
success = False

thread1 = myThread.run()
thread2 = myThread.program()

thread1.start()
thread2.start()

编辑: 我看到我自己的一些错误就像def函数的缩进一样,但即使在修复了我看到它并没有按预期工作之后。

0 个答案:

没有答案