在单独的线程中等待用户输入 [英] waiting for user input in separate thread

查看:126
本文介绍了在单独的线程中等待用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图完成一种产生等待用户输入的线程的方法;如果在10秒钟内没有输入任何输入,我希望脚本杀死生成的线程并继续进行处理.如果输入了文本,我有办法从线程取回输入,但是我没有办法让超时终止新产生的线程.

I am trying to accomplish a way to spawn a thread that waits for user input; if no input is entered within 10 seconds, I want the script to kill off the spawned thread and continue processing. I've got a way to get the input back from the thread if text is entered but I have no way to let the timeout kill off the newly spawned thread.

在下面的示例中,我是最接近的.我告诉新创建的线程,它是一个守护程序,它将在主脚本退出时退出.我的问题是线程将继续等待,直到脚本退出或用户输入了某些内容.

In the example below is the closest I have come. I tell the newly created thread that it is a daemon and it will exit when the main script exits. The issue that I have with this is that the thread will continue to wait until either the script exits, or the user has inputted something.

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]

我知道突然杀死线程不是最好的方法(

I know abruptly killing a thread isn't the best way to go (Related Link), but I don't know how to interrupt the new thread waiting on the raw_input

推荐答案

似乎无法计时用户输入.在SmartElectron提供的链接中,该解决方案不起作用,因为一旦请求raw_input,计时器就会暂停.

Looks like there is no way to time user input. In the link that SmartElectron provided, the solution does not work since the timer is halted once the raw_input is requested.

到目前为止最好的解决方案是:

Best solution so far is:

# 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

这篇关于在单独的线程中等待用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆