如何修复Python代码中的未绑定本地错误?
你能帮我解决这个问题吗? 在我运行它30秒之后,它会说“UnboundLocalError:赋值前引用的局部变量'command'”,你能帮我修复它吗?我尝试了很多关于如何修复这个错误的教程,但是我做不到如何修复Python代码中的未绑定本地错误?,python,Python,你能帮我解决这个问题吗? 在我运行它30秒之后,它会说“UnboundLocalError:赋值前引用的局部变量'command'”,你能帮我修复它吗?我尝试了很多关于如何修复这个错误的教程,但是我做不到 import speech_recognition as sr import pyttsx3 import pywhatkit import datetime import pyjokes listener = sr.Recognizer() engine = pyttsx3.init()
import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import pyjokes
listener = sr.Recognizer()
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].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)
command = command.lower()
if 'idiot' in command:
command = command.replace('idiot', '')
print(command)
except:
pass
return command
def run_idiot():
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')
print(time)
talk(time)
else:
talk('Please say the command again.')
while True:
run_idiot()
如果发生异常,您将没有
命令的定义
,因此返回它将导致无限本地错误。因此,您需要首先声明:
def take_command():
# declare 'command' variable outside try-except
command = ""
try:
with sr.Microphone() as source:
print('listening...')
voice = listener.listen(source)
command = listener.recognize_google(voice)
command = command.lower()
if 'idiot' in command:
command = command.replace('idiot', '')
print(command)
except:
pass
return command
请用完整的错误回溯更新您的问题。