Python 通过写入标准输入取消原始输入/输入?

Bry*_*ott 5 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)
Run Code Online (Sandbox Code Playgroud)

到目前为止,我所做的研究似乎表明“正确”取消线程是不可能的。我觉得流程对于这项任务来说太繁重了,但如果确实需要这样做,我并不反对使用它们。相反,我的想法是,如果计时器在没有用户输入的情况下完成,我可以向 stdin 写入一个值并优雅地关闭该线程。

那么,如何从主线程写入标准输入,以便子线程接受输入并正常关闭?谢谢!

Chr*_*her 10

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

import threading

response = None
def user_input():
    global response
    response = 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')
Run Code Online (Sandbox Code Playgroud)