thread.interrupt_main()在等待输入时不起作用

Amr*_*Amr 6 python multithreading timeout

我已经读过这种技术来超时阻止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
Run Code Online (Sandbox Code Playgroud)

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

更新:

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

Kie*_*ran 0

在 Unix 机器上,有一种方法可以完成您想要做的事情。看这篇文章: raw_input 和超时

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

在同一页面上还有适用于 Windows 操作系统的解决方案,但我还没有测试它是否有效。