ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-06-24 20:56:52  阅读:271  来源: 互联网

标签: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,以便子线程接受输入并正常关闭?
谢谢!

解决方法:

您可以使用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'

标签:python,multithreading,timer,raw-input
来源: https://codeday.me/bug/20190624/1281829.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有