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")
2

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

7 Comments

I need to halt user at the exact specified time otherwise your approach could have been useful.
Then you can't really use input()
maybe try using pygame for this sort of thing ;)
useful links ;)
|
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 :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.