Waiting for user input to a separate stream

I am trying to follow a way to create a thread that is waiting for user input; if no input is entered within 10 seconds, I want the script to destroy the spawned thread and continue processing. I have a way to return input from a stream if text is entered, but I have no way to allow a timeout to kill a newly created stream.

In the example below, the closest I came. I tell the newly created thread that it is a daemon and it will exit when the main script exits. The problem I encountered is that the thread will continue to wait until the script exits or the user has added nothing.

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]

, - ( ), , , raw_input

+5
2

, . , SmartElectron, , raw_input.

:

# 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
+3

, . ,

, , , . :

  • , .
  • , .

, .. , , . . *

,

+1

All Articles