UnboundLocalError:无法访问未与值关联的局部变量“命令”

问题描述 投票:0回答:4

如果在提示“listeng...”后大约 3 秒内没有给该程序发出语音命令,我会收到标题中提到的“UnboundLocalError”。

寻求有关如何让程序等待我的下一个语音命令而不关闭的建议。抱歉,如果问题很愚蠢,这是我的第一个节目。

程序如下:

import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia
import pyjokes

listener = sr.Recognizer()
engine = pyttsx3.init()
voices = engine.getProperty("voices")
engine.setProperty("voice", voices[0].id)


def talk(text):
    engine.say(text)
    engine.runAndWait()


def take_command():
    try:
        with sr.Microphone() as source:
            print("listening...")
            voice = listener.listen(source)
            command = listener.recognize_google(voice)
            if "computer" in command:
                command = command.replace("computer", "")
                print(command)
    except:
        pass
    return command


def run_alexa():
    command = take_command()
    print(command)

    if "play" in command:
        song = command.replace("play", "")
        talk("playing" + song)
        pywhatkit.playonyt(song)

    elif "time" in command:
        time = datetime.datetime.now().strftime("%I:%M %p")
        talk("the current time is " + time)

    elif "tell me about" in command:
        person = command.replace("tell me about", "")
        info = wikipedia.summary(person, 1)
        talk(info)

    elif "your favourite artist" in command:
        talk("Mr worldwide aka pitbull")

    elif "joke" in command:
        talk(pyjokes.get_joke())

    else:
        talk("what are you talking about willis")


while True:
    run_alexa()
Traceback (most recent call last):
  File "/Users/Alex/Documents/vscode/Virtual assistant/main.py", line 90, in <module>
    run_alexa()
  File "/Users/Alex/Documents/vscode/Virtual assistant/main.py", line 32, in run_alexa
    command = take_command()
              ^^^^^^^^^^^^^^
  File "/Users/Alex/Documents/vscode/Virtual assistant/main.py", line 29, in take_command
    return command
           ^^^^^^^
UnboundLocalError: cannot access local variable 'command' where it is not associated with a value
python voice
4个回答
1
投票

问题在于

take_command()
中某处发生异常,并且没有值与
command
关联,因此无法返回。

永远、永远不要使用裸露的

try: ... except: pass
,正如您所注意到的,您永远无法知道到底出了什么问题。

将该函数更改为类似的内容

def take_command():
    with sr.Microphone() as source:
        print("listening...")
        voice = listener.listen(source)
        command = listener.recognize_google(voice)
        if command and "computer" in command:
            command = command.replace("computer", "")
            return command
    return None

首先,从那里进行调试(该函数现在可能会引发异常)。


0
投票

在你的“take_command”def中,你必须为命令var分配一个值,无论它是否收到命令。

Ex: 

def take_command():
    try:
        with sr.Microphone() as source:
            print('listening...')
            voice = listener.listen(source)
            command = listener.recognize_google(voice)
            if 'computer' in command:
                command = command.replace('computer', '')
                print(command)
    except:
        command = ''
    return command

请注意,如果没有给出命令,那么我将使用“”向其传递一个空值。 只需输入 pass,它就会传递分配 var,这就是导致它在分配之前被引用的原因。

我希望这有帮助:)


0
投票

看起来问题可能出在您的

take_command
函数上。

def take_command():
    try:
        with sr.Microphone() as source:
            print("listening...")
            voice = listener.listen(source)
            command = listener.recognize_google(voice)
            if "computer" in command:
                command = command.replace("computer", "")
                print(command)
    except:
        pass
    return command

具体来说,您的退货声明是当前的问题。您返回

command
,但如果您的
try
块在设置
command
之前引发异常,则您将在
pass
子句中
except
。这意味着两件事:

  1. 你的 try 块有问题(现在不能确定那是什么)
  2. 您的代码可能会导致此错误,因为命令最终可能会被取消设置。

要修复 2,您可以更改 except to set 命令,例如:

def take_command():
    try:
        with sr.Microphone() as source:
            print("listening...")
            voice = listener.listen(source)
            command = listener.recognize_google(voice)
            if "computer" in command:
                command = command.replace("computer", "")
                print(command)
    except:
        command = None
    return command

但是我会看看如果你删除裸露的 except 子句并尝试改进那里会发生什么:

def take_command():
    with sr.Microphone() as source:
        print("listening...")
        voice = listener.listen(source)
        command = listener.recognize_google(voice)
        if "computer" in command:
            command = command.replace("computer", "")
            print(command)

    return command

这意味着发生的错误将被抛出而未处理,但我认为这在您的用例中可能更有用。


0
投票

尝试将您的 Python 版本和 Python 库更新到最新版本。如果这不起作用,请尝试在尝试文本之后启动命令变量

def take_command(): try: command = "" with sr.Microphone() as source: print('listening...') voice = listener.listen(source) command = listener.recognize_google(voice) if 'computer' in command: command = command.replace('computer', '') print(command) except: pass return command
尝试一下,看看会发生什么,如果问题仍然没有解决,请告诉我,我会帮你解决。 希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.