6

我已经阅读了这种技术来超时阻塞 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 上,这并没有给我最初想要的可移植性)。但是,我仍然想知道为什么上面的代码不起作用。

4

1 回答 1

0

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

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

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

于 2012-05-30T19:29:29.420 回答