0

can someone help me with this code? It's use is to make timed input for 2 seconds and it needs to print the last line even if the user did or didn't type something in the console (for that time). When I don't type in anything, after printing "Too Slow" it asks me for the same input, so I added IF, but it doesn't really notice it. I hope that someone can help me. Thanks!

import time
from threading import Thread
i = 0
answer = None

def check():
    time.sleep(2)
    if answer != None:
        return
    print("Too Slow") #prints this if nothing is typed in (for 2 seconds)
if i == 0:
  i = 1
  Thread(target = check).start()
  answer = input("Input something: ") #program doesn't even notice IF and asks me the second time for input

print("This should be printed instantly after printing Too Slow (when user doesn't input anything)")
AMC
  • 2,642
  • 7
  • 13
  • 35
zenvelop
  • 3
  • 3
  • _#program doesn't even notice IF and asks me the second time for input_ Which if statement? The one in the function? – AMC Apr 12 '20 at 23:54

1 Answers1

0

The return in the check function only causes the thread to be completed, but the call to input is independent of that thread and thus not interrupted when the check function completes. See this answer for an alternative solution using the signal module.

user7217806
  • 2,014
  • 2
  • 10
  • 12