Python 使用热键说话时在中间停止PySTX3

Python 使用热键说话时在中间停止PySTX3,python,python-3.x,if-statement,automation,sapi,Python,Python 3.x,If Statement,Automation,Sapi,我正在制作一个类似Jarvis的自动化机器人,我已经编写了一半的代码但是如果按下触发键,我想阻止它(PYSTX3)说话。主要问题是: try: speak('Searching wikipedia...') query = query.replace("wikipedia", "") results = wikipedia.summary(query, sen

我正在制作一个类似Jarvis的自动化机器人,我已经编写了一半的代码但是如果按下触发键,我想阻止它(PYSTX3)说话。主要问题是:

 try:
                speak('Searching wikipedia...')
                query = query.replace("wikipedia", "")
                results = wikipedia.summary(query, sentences=2)
                speak("According to wikipedia") 
                print(results)
                while True:
                    if keyboard.is_pressed("esc"):
                        break
                    else:
                        speak(results)

                                               
             except:
                 speak("Query not available on wikipedia. Please try something else")
                 print("Query not available on wikipedia. Please try something else")

如果我按下退出按钮,它不会停止

这是我的全部密码

import pyttsx3
import speech_recognition as sr
import datetime
import wikipedia
import webbrowser
import os
import keyboard  # using module keyboard


engine = pyttsx3.init('sapi5')
voices = engine.setProperty
#print(voices)

engine.getProperty('voice')
def speak(audio):
    engine.say(audio)
    engine.runAndWait()

def wishMe():
    hour = int(datetime.datetime.now().hour)
    if hour == 0 and hour < 12:
        speak("Good Morning!")
    elif hour >= 12 and hour < 18:
        speak("Good Afternoon!")
    else:
        speak("Good Evening!")
    speak("I am Ultron Sir. Please tell me how may i help you")



def takeCommand():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening.....")
        r.pause_threshold = 1
        r.energy_threshold = 300
        audio = r.listen(source)

    try:
        print("Recognizing...")
        query = r.recognize_google(audio, language = 'en-in')
        print(f"User said:  ",query)

    except Exception as e:

        print("Sorry sir, Couldn't recognize, please say again ...")
        return "None"
    return query


if __name__ == "__main__":
    wishMe()
    while True:
        
        query = takeCommand().lower()


        if 'wikipedia' in query:
            

             try:
                speak('Searching wikipedia...')
                query = query.replace("wikipedia", "")
                results = wikipedia.summary(query, sentences=2)
                speak("According to wikipedia") 
                print(results)
                while True:
                    if keyboard.is_pressed("esc"):
                        break
                    else:
                        speak(results)

                                               
             except:
                 speak("Query not available on wikipedia. Please try something else")
                 print("Query not available on wikipedia. Please try something else")


        elif 'open youtube' in query:
            webbrowser.open('youtube.com')

        elif 'open google' in query:
            webbrowser.open('google.com')

        elif '.com' in query:
            webbrowser.open(query)

        elif '.org' in query:
            webbrowser.open(query)

        elif 'the time' in query:
            strtime = datetime.datetime.now().strftime("%H:%M:%S")
            print(strtime)
            speak(strtime)

        elif 'open code' in query:
            codepath = "C:\\Program Files\\JetBrains\\PyCharm Community Edition 2019.2\\bin\\pycharm64.exe"
            os.startfile(codepath)

        elif 'exit ' in query:
            print("Thank You Sir.")
            speak("Thank you sir.")
            break
           

        elif 'who are you' in query:
            speak("I am Ultron, created by Mr. SD THE CODER and my mission is to serve mankind")


导入pyttsx3
将语音识别作为sr导入
导入日期时间
导入维基百科
导入网络浏览器
导入操作系统
导入键盘#使用模块键盘
engine=pyttsx3.init('sapi5')
voices=engine.setProperty
#印刷品(声音)
engine.getProperty('voice'))
def语音(音频):
引擎。比如说(音频)
engine.runAndWait()
def wishMe():
hour=int(datetime.datetime.now().hour)
如果小时=0且小时<12:
说:“早上好!”
elif小时数>=12且小时数<18:
说:“下午好!”
其他:
说:“晚上好!”
说话(“我是奥创先生,请告诉我我能为您做些什么”)
def takeCommand():
r=高级识别器()
使用sr.麦克风()作为源:
打印(“侦听…”)
r、 暂停\u阈值=1
r、 能量阈值=300
音频=r.listen(源)
尝试:
打印(“识别…”)
query=r.recognize\u谷歌(音频,语言='en-in')
打印(f“用户说:”,查询)
例外情况除外,如e:
打印(“对不起,先生,无法识别,请再说一遍…”)
返回“无”
返回查询
如果名称=“\uuuuu main\uuuuuuuu”:
wishMe()
尽管如此:
query=takeCommand().lower()
如果查询中有“wikipedia”:
尝试:
说话('搜索维基百科…')
query=query.replace(“维基百科”,“维基百科”)
结果=wikipedia.summary(查询,句子=2)
说话(“根据维基百科”)
打印(结果)
尽管如此:
如果按下键盘键(“esc”):
打破
其他:
发言(结果)
除:
说话(“维基百科上没有查询。请尝试其他内容”)
打印(“查询在维基百科上不可用。请尝试其他内容”)
elif查询中的“打开youtube”:
webbrowser.open('youtube.com')
elif查询中的“打开谷歌”:
webbrowser.open('google.com')
查询中的elif.com:
webbrowser.open(查询)
查询中的elif“.org”:
webbrowser.open(查询)
elif查询中的“时间”:
strtime=datetime.datetime.now().strftime(“%H:%M:%S”)
打印(标准时间)
说话(时间)
elif查询中的“打开代码”:
codepath=“C:\\Program Files\\JetBrains\\PyCharm Community Edition 2019.2\\bin\\pycharm64.exe”
os.startfile(代码路径)
查询中的elif“退出”:
打印(“谢谢您,先生”)
说(“谢谢你,先生。”)
打破
elif查询中的“您是谁”:
发言(“我是Ultron,由程序员SD先生创建,我的使命是为人类服务”)
如果你能帮助我,我会非常感谢你