【问题标题】:thread.interrupt_main() doesn't work when waiting for inputthread.interrupt_main() 在等待输入时不起作用
【发布时间】:2012-06-05 00:36:22
【问题描述】:

我已经阅读了这种技术来超时阻塞 IO 操作,问题是它似乎不起作用。例如:

import thread, threading
   
def read_timeout(prompt, timeout=10.0):
    timer = threading.Timer(timeout, thread.interrupt_main)
    s = ''
    timer.start()
    
    try:
        s = raw_input(prompt)
    except KeyboardInterrupt:
        print 'operation timed out.'
        
    timer.cancel()
    return s
    
s = read_timeout('enter input: ')

if s:
    print 'you entered: %s' % s

raw_input() 返回之前,这不会中断主线程。 任何帮助表示赞赏。

更新:

使用os.kill(os.getpid(), signal.SIGINT) 而不是thread.interrupt_main() 似乎可行(至少在Linux 上,这并没有给我最初想要的可移植性)。但是,我仍然想知道为什么上面的代码不起作用。

【问题讨论】:

    标签: python multithreading timeout


    【解决方案1】:

    在 Unix 机器上,有一种方法可以做你想做的事。看看这个帖子: raw_input and timeout

    只需去掉第5行末尾的逗号,否则程序终止后才会显示提示。

    在同一页面上还有适用于 Windows 操作系统的解决方案,但我尚未对其进行测试以了解它是否有效。

    【讨论】:

    • 我知道 select,但我一直在寻找可移植的东西 :) 我发布问题的主要原因是我想知道我的代码有什么问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多