My program is working with input() from user. I want to print "hey,are you there?"
when the user hasn't written anything in 5 seconds. For example, the user writes something, and stops typing. If the user waits more than 5 seconds, then I want to print "hey,are you there?"
. So far I tried this:
while True:
start=time.time()
x=input("enter something")
end=time.time()
dif=end-start
if 5<dif:
print("hey are you there?")
It didn't work as I expected, because it waits for the user. It's writing "hey are you there?"
after the user wrote something. But I expect that when the user doesn't type anything, it also means x==False
, I want to warn the user.
Update I tried this one:
import msvcrt
import time
time1 = 0
print('enter something: ')
while not msvcrt.kbhit():
time.sleep(1)
time1 +=1
if time1 == 5:
print("hey are you there?")
while msvcrt.kbhit():
x = input()
It didn't work either. It printed "hey are you there?"
after 5 seconds even x==True
. So far no solution, hope I explained what I need.
Seems like this works, but I'm using python 2.7:
import threading, time
class ValueGetter(object):
def __init__(self, wait_time_sec = 5.0):
self.stop_flag = True
self.wait_time_sec = wait_time_sec
def get_value(self):
self.stop_flag = False
p = threading.Thread(target=self.print_uthere)
p.start()
retval = raw_input('enter something:\n')
self.stop_flag = True
p.join()
return retval
def print_uthere(self):
tprint = tnow = time.clock()
while not self.stop_flag:
if tnow > (tprint + self.wait_time_sec):
print 'Are you there???'
tprint = time.clock()
time.sleep(0.01)
tnow = time.clock()
v = ValueGetter()
print v.get_value()
Here is a modified version that will reset the 5 sec timer whenever they enter a key. Windows only though.
import threading, time, msvcrt, sys
class ValueGetter(object):
def __init__(self, wait_time_sec = 5.0):
self.stop_flag = True
self.wait_time_sec = wait_time_sec
self.tprint = self.tnow = time.clock()
def get_value(self):
self.stop_flag = False
p = threading.Thread(target=self.print_uthere)
p.start()
print 'enter something:'
retval = ''
ch = ''
while not ch == '\r':
retval += ch
ch = msvcrt.getch()
sys.stdout.write(ch)
self.tprint = time.clock()
print
self.stop_flag = True
p.join()
return retval
def print_uthere(self):
self.tprint = self.tnow = time.clock()
while not self.stop_flag:
if self.tnow > (self.tprint + self.wait_time_sec):
print 'Are you there???'
self.tprint = time.clock()
time.sleep(0.01)
self.tnow = time.clock()
v = ValueGetter()
print v.get_value()