AI助手执行打开文件/视频操作后代码停止运行求助
问题描述
我正在开发一款带打开文件、搜索YouTube功能的小型AI助手,但发现执行打开文件或视频的操作后,代码就停了。下面是我的Python代码,还没试过任何解决办法,不知道问题出在哪。
import speech_recognition as sr import pyttsx3 import pywhatkit import datetime import wikipedia import pyjokes import webbrowser as wb import subprocess import os 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 'jarvis' in command: command = command.replace('jarvis', '') print(command) except: pass return command def run_jarvis(): command = take_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('Current time is ' + time) elif 'who is' in command: person = command.replace('who is', '') info = wikipedia.summary(person, 1) print(info) talk(info) elif 'joke' in command: talk(pyjokes.get_joke()) elif 'open twitch' in command: talk('opening your twitch') wb.open('https://www.twitch.tv/toasted_gg/') elif 'search'in command: search = command.replace ('search', '') pywhatkit.search(search) elif 'exit' in command: talk("Thanks for giving me your time") exit() elif 'who made you' in command: talk("i was made by 5 8 4 6") elif 'open minecraft' in command: subprocess.call('C:\Program Files\Feather Launcher\Feather Launcher.exe') talk('opening minecraft') elif 'open discord' in command: os.startfile('') talk('opening discord') else: talk('Please say the command again.') while True: run_jarvis()
问题原因及解决办法
核心问题
代码停止运行的关键原因是阻塞式调用卡死了程序流程:
pywhatkit.playonyt()、subprocess.call()这类函数会一直等待外部程序(浏览器、游戏客户端)关闭才会返回,只要程序没关,代码就卡在这一步,没法回到循环继续监听语音命令。os.startfile('')是空路径,执行时会直接抛出错误,导致整个程序崩溃终止。
具体修复步骤
- 把阻塞调用改成非阻塞
- 替换
subprocess.call()为subprocess.Popen(),它启动程序后立刻返回,不会等待程序关闭:
路径前加subprocess.Popen(r'C:\Program Files\Feather Launcher\Feather Launcher.exe')r前缀,避免反斜杠转义出问题。 pywhatkit.playonyt()本身是阻塞的,用线程包装让它在后台运行:import threading # 在play分支里替换原pywhatkit调用: threading.Thread(target=pywhatkit.playonyt, args=(song,)).start()
- 替换
- 修复Discord的空路径问题
填上Discord的正确启动路径,比如:
记得把os.startfile(r'C:\Users\你的用户名\AppData\Local\Discord\Update.exe --processStart Discord.exe')你的用户名换成实际系统用户名,同样加r前缀。 - 给run_jarvis加异常捕获
避免单个命令报错导致整个程序挂掉:def run_jarvis(): try: command = take_command() # 原来的所有判断逻辑都放在这里面 except Exception as e: print(f"执行错误:{e}") talk("刚才执行命令出了点问题,请再说一次") - 优化take_command的返回值
语音识别失败时,函数会返回None,后续判断会报错,改成返回空字符串:def take_command(): command = '' try: with sr.Microphone() as source: print('listening...') voice = listener.listen(source) command = listener.recognize_google(voice) command = command.lower() if 'jarvis' in command: command = command.replace('jarvis', '') print(command) except: pass return command
修复后的完整代码
import speech_recognition as sr import pyttsx3 import pywhatkit import datetime import wikipedia import pyjokes import webbrowser as wb import subprocess import os import threading 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(): command = '' try: with sr.Microphone() as source: print('listening...') voice = listener.listen(source) command = listener.recognize_google(voice) command = command.lower() if 'jarvis' in command: command = command.replace('jarvis', '') print(command) except: pass return command def run_jarvis(): try: command = take_command() if 'play' in command: song = command.replace('play', '').strip() talk(f'playing {song}') threading.Thread(target=pywhatkit.playonyt, args=(song,)).start() elif 'time' in command: time = datetime.datetime.now().strftime('%I:%M %p') talk(f'Current time is {time}') elif 'who is' in command: person = command.replace('who is', '').strip() info = wikipedia.summary(person, 1) print(info) talk(info) elif 'joke' in command: talk(pyjokes.get_joke()) elif 'open twitch' in command: talk('opening your twitch') wb.open('https://www.twitch.tv/toasted_gg/') elif 'search' in command: search = command.replace('search', '').strip() pywhatkit.search(search) elif 'exit' in command: talk("Thanks for giving me your time") exit() elif 'who made you' in command: talk("i was made by 5 8 4 6") elif 'open minecraft' in command: subprocess.Popen(r'C:\Program Files\Feather Launcher\Feather Launcher.exe') talk('opening minecraft') elif 'open discord' in command: # 替换成你的Discord实际路径 os.startfile(r'C:\Users\你的用户名\AppData\Local\Discord\Update.exe --processStart Discord.exe') talk('opening discord') else: if command: talk('Please say the command again.') except Exception as e: print(f"执行错误:{e}") talk("刚才执行命令出了点问题,请再说一次") while True: run_jarvis()
内容的提问来源于stack exchange,提问作者GX12
相关产品推荐
相关产品推荐

