Python 我尝试使用异常来保存应用程序,但它显示(UnboundLocalError:localvariable';result';在赋值之前引用)

Python 我尝试使用异常来保存应用程序,但它显示(UnboundLocalError:localvariable';result';在赋值之前引用),python,Python,这是我的代码,它正在制造问题,我只想让我的麦克风继续尝试聆听 def takeCommand(self): print("listening") with sr.Microphone() as source: audio = MySiri.listner.listen(source,phrase_time_limit=3) try: result = MySiri.listner.recognize_google(audio)

这是我的代码,它正在制造问题,我只想让我的麦克风继续尝试聆听

def takeCommand(self):
    print("listening")
    with sr.Microphone() as source:
        audio = MySiri.listner.listen(source,phrase_time_limit=3)

    try:
        result = MySiri.listner.recognize_google(audio)
        print(result)
    except Exception as e:
        print(e)
        self.speak("sorry,repeat")
    return result

问题是,如果您的代码在
result=MySiri.listner.recognize\u google(audio)
&中出现异常,则异常中没有名为
result
的变量,请尝试此操作

def takeCommand(self):
    print("listening")
    with sr.Microphone() as source:
        audio = MySiri.listner.listen(source,phrase_time_limit=3)

    try:
        result = MySiri.listner.recognize_google(audio)
        print(result)
    except Exception as e:
        print(e)
        result = 'sorry, repeat'
        self.speak("sorry,repeat")
    return result