1

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")
12944qwerty
  • 2,001
  • 1
  • 10
  • 30
marius19
  • 11
  • 2
  • Does this answer your question? [Keyboard input with timeout?](https://stackoverflow.com/questions/1335507/keyboard-input-with-timeout) – Akida Dec 09 '21 at 15:03
  • I also checked this answer.. it does not work on Windows. – marius19 Dec 09 '21 at 15:41
  • did you try the other answers like https://stackoverflow.com/a/41812246/16841774 ? – Akida Dec 10 '21 at 08:28
  • Yes, I tried this also... still did not work. After long time searching I found a working code! Here is the link for others: https://pypi.org/project/pytimedinput/ The only point is that you have to run the code in cmd... Question can be closed. Or should I do that? – marius19 Dec 10 '21 at 09:28
  • you can answer your question with the project you found and it's limitations and accept your own answer. Or you could delete your question if you think that this won't help anybody in the future. – Akida Dec 10 '21 at 10:13

1 Answers1

0

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/

marius19
  • 11
  • 2