问题描述
首先,我使用的是 python 2.7.5 和 Windows x64,我的应用程序针对这些参数.
For starters, I'm on python 2.7.5 and Windows x64, my app is targeted at those parameters.
我需要一种在经过一定时间后取消 raw_input 的方法.目前我的主线程启动了两个子线程,一个是计时器(threading.Timer),另一个触发 raw_input.它们都向主线程监视的 Queue.queue 返回一个值.然后它对发送到队列的内容进行操作.
I'm in need of a way to cancel a raw_input after a certain amount of time has passed. Currently I have my main thread starting two child threads, one is the timer (threading.Timer) and the other fires the raw_input. These both return a value to a Queue.queue that the main thread monitors. It then 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'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 写入一个值并优雅地关闭该线程.
The research that I've done so far seems to say that it's not possible to "correctly" cancel a thread. I feel that processes are too heavy for the task, though I'm not opposed to using them if that's what really needs to be done. Instead, my thought is that if the timer finishes with no user input, I can write a value to stdin and close that thread gracefully.
那么,如何从主线程写入 stdin 以便子线程接受输入并正常关闭?谢谢!
So, how do I write to stdin from the main thread so that the child thread accepts the input and closes gracefully?Thanks!
推荐答案
您可以使用 threading.Thread.join 方法来处理超时.让它工作的关键是设置守护进程属性,如下所示.
You can use the threading.Thread.join method to handle the timeout. The key to getting it working is to set the daemon attribute as shown below.
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'
这篇关于Python 通过写入标准输入取消原始输入/输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!