gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:19:49 24 4
gpt4 key购买 nike

我读到过这种使阻塞 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 上,它不' 给我最初想要的便携性)。但是,我仍然想知道为什么上面的代码不起作用。

最佳答案

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

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

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

关于python - thread.interrupt_main() 在等待输入时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10821995/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com