【问题标题】:Python cancel raw_input/input via writing to stdin?Python通过写入标准输入取消raw_input/input?
【发布时间】:2013-10-18 17:10:25
【问题描述】:

对于初学者,我使用的是 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)

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

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

【问题讨论】:

    标签: python multithreading timer raw-input


    【解决方案1】:

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

    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')
    

    【讨论】:

    • 我相信这会像我的情况(一个 CLI 程序)一样工作,我不在乎在我们等待输入时主线程是否阻塞。谢谢!
    • 太棒了。这是唯一实际执行正确超时 input(对于 Python 3)的示例,而无需再次按 Enter 键以使代码继续运行。
    猜你喜欢
    • 2016-07-11
    • 2021-03-05
    • 2010-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-25
    • 1970-01-01
    • 2016-05-07
    相关资源
    最近更新 更多