好的,我已经实现了它:D.
#!/usr/bin/env python
import sys
from select import select
def main(argv):
timeout = 3
prompt = '> '
max_chars = 3
# set raw input mode if relevant
# it is necessary to make stdin not wait for enter
try:
import tty, termios
prev_flags = termios.tcgetattr(sys.stdin.fileno())
tty.setraw(sys.stdin.fileno())
except ImportError:
prev_flags = None
buf = ''
sys.stderr.write(prompt)
while True: # main loop
rl, wl, xl = select([sys.stdin], [], [], timeout)
if rl: # some input
c = sys.stdin.read(1)
# you will probably want to add some special key support
# for example stop on enter:
if c == '\n':
break
buf += c
# auto-output is disabled as well, so you need to print it
sys.stderr.write(c)
# stop if N characters
if len(buf) >= max_chars:
break
else:
# timeout
break
# restore non-raw input
if prev_flags is not None:
termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, prev_flags)
# and print newline
sys.stderr.write('\n')
# now buf contains your input
# ...
if __name__ == "__main__":
main(sys.argv[1:])
Run Code Online (Sandbox Code Playgroud)
它相当不完整; 我只是给它一些值来测试它.几句解释:
curses
,end_time
)增加它,然后end_time - current_time
在超时时间内传递秒数select()
,