Как добавить опцию по умолчанию и тайм-аут в функцию Python?Python

Программы на Python
Ответить
Anonymous
 Как добавить опцию по умолчанию и тайм-аут в функцию Python?

Сообщение Anonymous »

Я хочу иметь возможность создать меню «Опции», в котором пользователь может выбрать между выполнением двух функций, которые я смог сделать, но хочу добавить опцию тайм -аута и по умолчанию, если ответа нет. Я спросил Chatgpt о том, как добавить это, и он работает, но когда нет ответа, он запускает опцию по умолчанию, но затем снова запрашивает ввод. < /P>
Как я могу его получить Не спрашивайте другой ввод, если он времена выходит, и запускает опцию по умолчанию?def function_1():
print('Function 1 is running!')

def function_2():
print('Function 2 is running!')

# Map user choices to functions
function_map = {'1': function_1,
'2': function_2}

def main():
while True:
print('Choose an option:\n 1: Run Function 1 \n 2: Run Function 2 \n q: Quit')
user_choice = input('Enter your choice: ').strip().lower()

if user_choice == 'q':
print('Exiting program.')
break
elif user_choice in function_map:
# Call the selected function
function_map[user_choice]()
break
else:
print('Invalid choice. Please try again.')

if __name__ == '__main__':
main()

Chatgpt
import threading

def function_1():
print("Function 1 is running!")

def function_2():
print("Function 2 is running!")

# Map user choices to functions
function_map = {
"1": function_1,
"2": function_2
}

# Timeout handler
def input_with_timeout(prompt, timeout, default):
user_input = [None]

def get_input():
user_input[0] = input(prompt).strip().lower()

thread = threading.Thread(target=get_input)
thread.start()
thread.join(timeout)
if thread.is_alive():
print(f"\nNo input detected within {timeout} seconds. Defaulting to option {default}.")
return default

return user_input[0]

def main():
while True:
print("Choose an option:")
print("1: Run Function 1")
print("2: Run Function 2")
print("q: Quit")

# Prompt user with a 5-second timeout
user_choice = input_with_timeout("Enter your choice: ", timeout=5, default="1")

if user_choice == "q":
print("Exiting program.")
break
elif user_choice in function_map:
# Call the selected function
function_map[user_choice]()
break # Exit after a valid choice
else:
print("Invalid choice. Please try again.")

if __name__ == "__main__":
main()


Подробнее здесь: https://stackoverflow.com/questions/793 ... n-function
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»