Python助手程序if语句异常执行及返回监听问题求助
Hey there! Let's tackle your two issues step by step with concrete fixes:
Issue 1: Random if statement execution & unexpected errors
Looking at your check_audio() function, there are several logic bugs causing the random behavior and errors:
Key Problems Identified:
- Unintended
ifexecution: The finalif any(y.lower() in cmdtext for y in ["Rick Roll", "rickroll"])is a standaloneif, not part of theelifchain. This means it runs every time after the previous conditions, even if a priorelifmatched. Its attachedelsealso overrides valid commands, leading to "I don't recognise this command" even when the command worked. - Broken condition check:
if "days" or "day" in cmdtextis logically incorrect—it evaluates toTruealways because"days"is a non-empty string (truthy). You need to check if either substring exists incmdtext. - Incorrect type check:
if w2n.word_to_num(cmdtext) == int:compares a number to theintclass, which will never be true. Useisinstance()instead to check if the result is an integer. - Unassigned variable increment:
quitcount + 1doesn't update the variable—you needquitcount += 1. - Exception string concatenation:
print("Error" + e)will throw a TypeError because you can't concatenate a string with an Exception object. Use an f-string instead. - Useless "go back" loop: The
while "go back" in cmdtext: breakdoes nothing; we'll adjust this to trigger a return to keyword listening.
Fixed check_audio() Function:
def check_audio(): cmdtext = get_audio() print("CMDTEXT-You said: " + cmdtext) # Track if we executed a valid command to avoid false "unrecognised" messages command_executed = False try: if any(x.lower() in cmdtext for x in ["Hey", "Hello", "Ahoi"]): hellos = ["Hey there!", "Hi!", "How's it going?", "Well.. Hello there!"] stalk(random.choice(hellos)) command_executed = True elif "schedule" in cmdtext: if "days" in cmdtext or "day" in cmdtext: num_match = re.search(r'\d+', cmdtext) if num_match: word_num = w2n.word_to_num(cmdtext) if isinstance(word_num, int): get_events(word_num, service) command_executed = True elif "Week" in cmdtext: word_num = w2n.word_to_num(cmdtext) days = word_num * 7 if isinstance(word_num, int) else 7 get_events(days, service) command_executed = True elif "quit" in cmdtext: global quitcount # Ensure we modify the global variable quitcount += 1 print(quitcount) byebyes = ["Bye Bye!", "See you later!", "Cya later alligator", "See you soon!"] stalk(random.choice(byebyes)) quit() elif "go back" in cmdtext: # Return early to trigger keyword listening again command_executed = True return elif "open" in cmdtext: if "Notepad" in cmdtext: subprocess.Popen([r'C:\Program Files\Notepad++\Notepad++.exe']) elif "Chrome" in cmdtext: subprocess.Popen([r'C:\Program Files (x86)\Google\Chrome\Application\Chrome.exe']) elif "Discord" in cmdtext: subprocess.Popen([r'C:\Users\CelestialMavis\AppData\Local\Discord\app-0.0.306\Discord.exe']) elif "Steam" in cmdtext: subprocess.Popen([r'C:\Program Files (x86)\Steam\Steam.exe']) else: stalk("I did not recognize that program name") command_executed = True elif any(y.lower() in cmdtext for y in ["Rick Roll", "rickroll"]): webbrowser.open_new_tab("https://www.youtube.com/watch?v=dQw4w9WgXcQ") command_executed = True # Only print unrecognized command if no valid action ran if not command_executed: print("I don't recognise this command") except Exception as e: print(f"Error: {e}") stalk("I didn't quite get that")
Issue 2: Stuck in command listening instead of returning to keyword detection
Your current setup creates nested infinite loops that trap the program in command listening. Here's how to fix it:
Key Problems Identified:
- Broken
mainOpsloop:while beginop != "Quit" or "Exit"is logically flawed—it always evaluates toTruebecause"Exit"is truthy. Worse,beginopisn't even defined in the function. - Nested infinite loops: When the keyword is detected, you enter
while True: mainOps(), andmainOpsitself has a loop callingcheck_audio()—this creates an unbreakable cycle of command listening.
Fixed Code for Keyword Listening & mainOps:
def mainOps(): # Run only one command check, then return to keyword listening SEGI.check_audio() # Listen for Keyword from Microphone! recog = spcrec.Recognizer() cmdwrd = 'hey Wendy' cmdwrdqt = 'quit' with spcrec.Microphone() as source: print(f"Hey! Im VASE") print(f"Please say {cmdwrd.capitalize()} to speak with Wendy or say {cmdwrdqt.capitalize()} to End the program") whattosay = f"Please say {cmdwrd} to speak with Wendy or say {cmdwrdqt} to End the program" vtts.VaseTTS(whattosay) vso = "Vase Online" print(vso) while True: try: audio_text = STa.get_audio() # Update STa.check_audio to accept audio text and check for the keyword if cmdwrd.lower() in audio_text.lower(): print("Keyword detected! Listening for commands...") # Run one command cycle, then return to keyword listening mainOps() elif cmdwrdqt.lower() in audio_text.lower(): stalk("Goodbye!") break else: print(f"Please speak again—say '{cmdwrd}' to activate Wendy or '{cmdwrdqt}' to quit.") except Exception as e: print('No keywords detected, please say the command to begin again') print(e)
Quick Note:
I simplified the keyword check directly in the loop instead of relying on STa.check_audio()—if you want to keep using that function, adjust it to accept the audio text as a parameter and return True when the keyword is present.
This setup ensures that after executing one command, the program returns to listening for the activation keyword instead of getting stuck in command mode.
内容的提问来源于stack exchange,提问作者IlCelestialI

