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
in your case don't worry for close the thread abruptly. In link, say
It is generally a bad pattern to kill a thread abruptly, in python and in any language. Think of the following cases:
- the thread is holding a critical resource that must be closed properly.
- the thread has created several other threads that must be killed as well.
Close database connection, files opened, etc. resources that need be
closed properly, in this cases close the thread properly is
fundamental. In this case your solution is valid.*
If this solution does not satisfy you can use How to set time limit on input