Я хочу иметь возможность создать меню «Опции», в котором пользователь может выбрать между выполнением двух функций, которые я смог сделать, но хочу добавить опцию тайм -аута и по умолчанию, если ответа нет. Я спросил 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
Как добавить опцию по умолчанию и тайм-аут в функцию Python? ⇐ Python
Программы на Python
-
Anonymous
1737990327
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()
[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антехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия