Python cancel raw_input / input via write to stdin?

For starters, I'm on python 2.7.5 and Windows x64, my application targets these options.

I need a way to cancel raw_input after a while. Currently, I have a main thread starting two child threads, one a timer (threading.Timer) and the other starts raw_input. They return a value in Queue.queue, which tracks the main thread. Then it acts on what is sent to the queue.

# snip...
q = Queue.queue()
# spawn user thread
user = threading.Thread(target=user_input, args=[q])
# spawn timer thread (20 minutes)
timer = threading.Timer(1200, q.put, ['y'])
# wait until we get a response from either
while q.empty():
    time.sleep(1)
timer.cancel()

# stop the user input thread here if it still going

# process the queue value
i = q.get()
if i in 'yY':
    # do yes stuff here
elif i in 'nN':
    # do no stuff here

# ...snip

def user_input(q):
    i = raw_input(
        "Unable to connect in last {} tries, "
        "do you wish to continue trying to "
        "reconnect? (y/n)".format(connect_retries))
    q.put(i)

, , , , "" . , , , . , , , stdin .

, stdin , ? !

+4
1

threading.Thread.join -. daemon, .

import threading

response = None
def user_input():
    global response
    response = raw_input("Do you wish to reconnect? ")

user = threading.Thread(target=user_input)
user.daemon = True
user.start()
user.join(2)
if response is None:
    print 
    print 'Exiting'
else:
    print 'As you wish'
+2

All Articles