def input_with_timeout_windows(prompt, timeout, default):
start_time = time.time()
print prompt,
sys.stdout.flush()
input = ''
while True:
if msvcrt.kbhit():
chr = msvcrt.getche()
if ord(chr) == 13: # enter_key
break
elif ord(chr) >= 32: #space_char
input += chr
if len(input) == 0 and (time.time() - start_time) > timeout:
break
if len(input) > 0:
return input
else:
return default
python类getche()的实例源码
def getreply():
if sys.stdin.isatty():
return input('?')
else:
if sys.platform[:3]=="win":
import msvcrt
msvcrt.putch(b'?')
key=msvcrt.getche()
msvcrt.putch(b'\n')
return key
else:
assert False,'platform not supported'
# linux?:open('/dev/tty').readline()[:-1]