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

问题描述 投票:0回答:2

我读过有关这种超时阻塞 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
2个回答
2
投票

根据API的最新文档:https://docs.python.org/3/library/_thread.html#thread.interrupt_main

这不会发出相应的信号,而是安排对关联处理程序的调用(如果存在)。

并且该调用是在主线程中当前阻塞调用之后执行的。

另一方面,更新中提到的

os.kill
解决方案会立即向主线程发出信号。

抱歉,问题提出已经有一段时间了,但希望它仍然有帮助。


0
投票

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

只需删除第5行末尾的逗号,否则直到程序终止才会显示提示。

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

© www.soinside.com 2019 - 2024. All rights reserved.