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

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

Сообщение Anonymous »

Я хочу иметь возможность создать меню параметров, в котором пользователь может выбирать между запуском двух функций, что я смог сделать, но хочу добавить тайм-аут и параметр по умолчанию для запуска, если нет ответа. Я попросил ChatGPT предоставить код о том, как это добавить, и он работает, но когда нет ответа, он запускает параметр по умолчанию, но затем снова запрашивает ввод.
Как я могу его получить не запрашивать другой ввод, если время ожидания истекло и запускается опция по умолчанию?
Мой код
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»