2

我有一个 GUI 程序,它也应该可以通过 CLI 控制(用于监控)。CLI 使用 raw_input 在 while 循环中实现。如果我通过 GUI 关闭按钮退出程序,它会挂在 raw_input 中并且在获得输入之前不会退出。

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

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

我搜索了几个小时的 stackoverflow,我知道该主题有很多答案,但是真的没有平台独立的解决方案来拥有非阻塞 CLI 阅读器吗?

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

谢谢

4

2 回答 2

2

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

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()
于 2011-01-04T12:52:35.263 回答
1

根据您使用的 GUI 工具包,找到一种方法将事件侦听器连接到关闭窗口操作并使其调用win32api.TerminateProcess(-1, 0).

作为参考,在 Linux 调用sys.exit()工作。

于 2011-01-04T09:00:03.427 回答