Python通过写入stdin取消raw_input / input?

时间:2013-10-18 17:10:26

标签: python multithreading timer raw-input

对于初学者,我使用的是python 2.7.5和Windows x64,我的应用程序针对的是这些参数。

我需要一种方法来在经过一定时间后取消raw_input。目前我有我的主线程启动两个子线程,一个是计时器(threading.Timer),另一个是激活raw_input。这两个都返回一个值到主线程监视的Queue.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's 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,以便子线程接受输入并正常关闭? 谢谢!

1 个答案:

答案 0 :(得分:4)

您可以使用threading.Thread.join方法来处理超时。让它工作的关键是设置守护进程属性,如下所示。

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'