Python:当卡在阻止raw_input时如何退出CLI? [英] Python: How to quit CLI when stuck in blocking raw_input?

查看:228
本文介绍了Python:当卡在阻止raw_input时如何退出CLI?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个GUI程序,该程序也应该可以通过CLI(用于监视)进行控制. CLI使用raw_input在while循环中实现. 如果我通过GUI关闭按钮退出程序,则该程序将挂在raw_input上,直到获得输入后才退出.

I have a GUI program which should also be controllable via CLI (for monitoring). The CLI is implemented in a while loop using raw_input. If I quit the program via a GUI close button, it hangs in raw_input and does not quit until it gets an input.

如何在不输入输入的情况下立即中止raw_input?

How can I immediately abort raw_input without entering an input?

我在WinXP上运行它,但我希望它独立于平台,它也应该在Eclipse中运行,因为它是开发人员工具. Python版本是2.6.

I run it on WinXP but I want it to be platform independent, it should also work within Eclipse since it is a developer tool. Python version is 2.6.

我在stackoverflow上搜索了几个小时,并且知道该主题有很多答案,但是真的没有平台无关的解决方案来拥有无阻塞的CLI读取器吗?

I searched stackoverflow for hours and I know there are many answers to that topic, but is there really no platform independent solution to have a non-blocking CLI reader?

如果没有,克服这个问题的最佳方法是什么?

If not, what would be the best way to overcome this problem?

谢谢

推荐答案

这可能不是最佳解决方案,但是您可以使用线程模块,其具有功能thread.interrupt_main().因此可以运行两个线程:一个使用raw_input方法,另一个可以发出中断信号.上层线程引发KeyboardInterrupt异常.

That's not maybe the best solution but you could use the thread module which has a function thread.interrupt_main(). So can run two thread : one with your raw_input method and one which can give the interruption signal. The upper level thread raise a KeyboardInterrupt exception.

import thread
import time

def main():
    try:
        m = thread.start_new_thread(killable_input, tuple())
        while 1:
            time.sleep(0.1) 
    except KeyboardInterrupt:
        print "exception" 

def killable_input():
    w = thread.start_new_thread(normal_input, tuple())
    i = thread.start_new_thread(wait_sometime, tuple())


def normal_input():
    s = raw_input("input:")


def wait_sometime():
    time.sleep(4) # or any other condition to kill the thread
    print "too slow, killing imput"
    thread.interrupt_main()

if __name__ == '__main__':
    main()

这篇关于Python:当卡在阻止raw_input时如何退出CLI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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