用户 select 在 Python 中的输入模式之间的功能

Function for user to select between input modes in Python

我正在尝试在 python 中做一些助手类的事情,所以基本上我想要的是它要求用户在两种输入模式(即文本或语音输入)之间 select。

但问题是我无法在主代码中实现它。下面是我尝试制作的示例代码:

import keyboard
import speech_recognition as sr



def takecommandti():
    print(" ")
    rt=input(">>")
    return rt.lower()

def takeCommandsi():     
        print("Listening....")
        r = sr.Recognizer()
        r.dynamic_energy_threshold=False
        r.energy_threshold=4000
        r.pause_threshold = 1
        with sr.Microphone() as source:
            r.adjust_for_ambient_noise(source)
            audio = r.listen(source)
            said=""
        try:
            print("Recognizing....")
            said = r.recognize_google(audio,language='en-in')
            print(f"You Said : {said}\n")
        except sr.UnknownValueError :
            print("could not understand audio \n ~Trying Again~")
            return takeCommandsi()
        except sr.RequestError as e:
            print("Could not request results, check your internet connection; {0}".format(e))
            return "None"
        return said.lower()


input_mode_selection_variable = 0
print("Please Select in which input Mode you want to Use :) ")
print("1.Press 't' for Text Input Mode \n2.Press 's' for Speech Input Mode ")

while True :
    if keyboard.is_pressed('t'):
        print('You have successfully Selected : Text Input Mode')
        input_mode_selection_variable=False
        break
    elif keyboard.is_pressed('s'):
        print('You have successfully Selected : Speech Input Mode')
        input_mode_selection_variable=True
        break
    
def takecommand():
    if input_mode_selection_variable == False:
        takecommandti()
    elif input_mode_selection_variable ==True:
        takeCommandsi()

我该怎么做?

我不认为 input_mode_selection_variable 在其他脚本中使用 takecommand() 函数时会起作用。

所以我终于更改了代码中的一些逻辑,现在它对我来说工作正常。

这是我现在一直在使用的代码:

import time
import keyboard
from rich import print


def mode_select():
    print("Please Select in wich input Mode you want to Use :) ")
    print("1.Press 't' for Text Input Mode\n2.Press 's' for Speech Input Mode ")

    while True : 
        if keyboard.is_pressed('t'):
            print('You have successfully Selected : Text Input Mode')
            mode_var= 0
            time.sleep(2)
            break
        elif keyboard.is_pressed('s'):
            print('You have successfully Selected : Speech Input Mode')
            mode_var= 1
            time.sleep(2)
            break           
    return mode_var

#sample how it will be used for selecting modes : 
a=mode_select()
if a==0:
    #takecommandti()
    print("things realted to text input happen in main script :)")
elif a==1:
    #takecommandsi()    
    print("things realted to speech_input happen in main script :)")