Search code examples
pythoninputpycharm

Set default value for input-function after timeout in python


I have searched for quite a long time in the internet but could not find a proper answer for my problem in Pyhton 3.6 on Windows 10.

In the beginning, the program should ask if the user would like to give an answer to the question "Yes [y] or No [n]? ". When the user answers with "y" or "n" everything is fine.

The problem is this: After 5 seconds the input-function should terminate and if nothing was answered a default value (i.e. "n") should be set and the programm should continue automatically to run. Unfortunatley, is just continues to run when I press "enter".

My code at the moment is the following:

from threading import Timer

answer = "n"
timeout = 5
t = Timer(timeout, print, ['\nDefault setting: MA = n'])
t.start()
prompt = "Yes [y] or No [n]?: "
user_input = input(prompt)
t.cancel()

if user_input == "n" or user_input == "y":
    answer = user_input

if answer == "n":
    print("Answer is n")
else:
    print("Answer is y")

Solution

  • This example helped me:

    from pytimedinput import timedInput
    userText, timedOut = timedInput("Please, do enter something: ")
    if(timedOut):
       print("Timed out when waiting for input.")
       print(f"User-input so far: '{userText}'")
    else:
       print(f"User-input: '{userText}'")
    

    https://pypi.org/project/pytimedinput/