Я хочу иметь возможность создать меню параметров, в котором пользователь может выбирать между запуском двух функций, что я смог сделать, но хочу добавить тайм-аут и параметр по умолчанию для запуска, если нет ответа. Я попросил 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
Как добавить опцию по умолчанию и тайм-аут в функцию Python? ⇐ Python
Программы на Python
-
Anonymous
1737987064
Anonymous
Я хочу иметь возможность создать меню параметров, в котором пользователь может выбирать между запуском двух функций, что я смог сделать, но хочу добавить тайм-аут и параметр по умолчанию для запуска, если нет ответа. Я попросил ChatGPT предоставить код о том, как это добавить, и он работает, но когда нет ответа, он запускает параметр по умолчанию, но затем снова запрашивает ввод.
Как я могу его получить не запрашивать другой ввод, если время ожидания истекло и запускается опция по умолчанию?
[b]Мой код[/b]
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()
[b]ChatGPT[/b]
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()
Подробнее здесь: [url]https://stackoverflow.com/questions/79391085/how-to-add-a-default-option-and-timeout-into-a-python-function[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия