问题
Python3's input()
seems to take old std input between two calls to input()
. Is there a way to ignore the old input, and take new input only (after input()
gets called)?
import time
a = input('type something') # type "1"
print('\ngot: %s' % a)
time.sleep(5) # type "2" before timer expires
b = input('type something more')
print('\ngot: %s' % b)
output:
$ python3 input_test.py
type something
got: 1
type something more
got: 2
回答1:
You can flush the input buffer prior to the second input()
, like so
import time
import sys
from termios import tcflush, TCIFLUSH
a = input('type something') # type "1"
print('\ngot: %s' % a)
time.sleep(5) # type "2" before timer expires
tcflush(sys.stdin, TCIFLUSH) # flush input stream
b = input('type something more')
print('\ngot: %s' % b)
来源:https://stackoverflow.com/questions/55525716/python-input-takes-old-stdin-before-input-is-called