I am trying to accomplish a way to spawn a thread that waits for user input; if no input is entered within 10 seconds, I want the script to kill off the spawned thread and continue processing. I've got a way to get the input back from the thread if text is entered but I have no way to let the timeout kill off the newly spawned thread.
In the example below is the closest I have come. I tell the newly created thread that it is a daemon and it will exit when the main script exits. The issue that I have with this is that the thread will continue to wait until either the script exits, or the user has inputted something.
shared_var = ['1']
def run(ref):
ref[0] = raw_input("enter something: ")
print "shared var changed to '%s'" % (ref[0])
thread = threading.Thread(target=run, args=(shared_var,))
thread.daemon = True
thread.start()
time.sleep(10) # simplified timeout
#Need some way to stop thread if no input has been entered
print "shared var = " + shared_var[0]
I know abruptly killing a thread isn't the best way to go (Related Link), but I don't know how to interrupt the new thread waiting on the raw_input
Looks like there is no way to time user input. In the link that SmartElectron provided, the solution does not work since the timer is halted once the raw_input is requested.
Best solution so far is:
# Declare a mutable object so that it can be pass via reference
user_input = [None]
# spawn a new thread to wait for input
def get_user_input(user_input_ref):
user_input_ref[0] = raw_input("Give me some Information: ")
mythread = threading.Thread(target=get_user_input, args=(user_input,))
mythread.daemon = True
mythread.start()
for increment in range(1, 10):
time.sleep(1)
if user_input[0] is not None:
break
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With