2

Under certain time I need user to input some specific sentence.

For example, user should write below sentence under 10 seconds:

Hello! World.

However, if user is unable to finish complete sentence then whatever one wrote should be accepted. So, if one is able to write only Hello! Wo then it should be stored.

Problem - If user doesn't hit Return/Enter before time then nothing is saved. How to overcome this? Here's my approach -

import time
from threading import Thread

print('Hello! World')
user = None

def check():
    time.sleep(10)
    if user != None:
        return
    print ("Too Slow")

Thread(target = check).start()

user = input("Enter above string: \n")
sync11
  • 1,224
  • 2
  • 10
  • 23

2 Answers2

3

I would take a different approach (that doesn't require threading); I would save the current dat end time just before you print "hello world" and then compare the current time afterwards.

from datetime import datetime, timedelta

start = datetime.now()
print("Hello world!")
if input() == "Hellow world!" and datetime.now()<=start + timedelta(seconds = 10):
    #the user got it right
else:
    #the user was either too slow or got it wrong
Treehee
  • 117
  • 1
  • 2
  • 11
1

To do so you'd have to create your own window with your very own event handler that would detect whenever the user hit a key on his keyboard. Standard input() method or even customized textControl widgets in wxPython are cool, but always waits till user has hit the Enter key. So i unfortunately think that you'd have to use some GUI library (such as wxpython, which comes up with your OS's native look and a bunch of useful widgets), and take care of event handling by itself. If you'd rather implement a timeout than that GUI, you could run user input in one thread and immediately start the second one with the timer. Then write a handler that'd kill the inputThread when the timer finished and vice versa. Hope i helped :)