这可能不是最好的解决方案,但您可以使用具有 function的线程模块thread.interrupt_main()
。所以可以运行两个线程:一个使用您的 raw_input 方法,一个可以发出中断信号。上层线程引发 KeyboardInterrupt 异常。
import thread
import time
def main():
try:
m = thread.start_new_thread(killable_input, tuple())
while 1:
time.sleep(0.1)
except KeyboardInterrupt:
print "exception"
def killable_input():
w = thread.start_new_thread(normal_input, tuple())
i = thread.start_new_thread(wait_sometime, tuple())
def normal_input():
s = raw_input("input:")
def wait_sometime():
time.sleep(4) # or any other condition to kill the thread
print "too slow, killing imput"
thread.interrupt_main()
if __name__ == '__main__':
main()