python 在调用 input() 之前,input() 采用旧标准输入

python input() takes old stdin before input() is called

Python3 的 input() 似乎在两次调用 input() 之间采用旧的标准输入。有没有办法忽略旧输入,只接受新输入(在调用 input() 之后)?

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)

输出:

$ python3 input_test.py
type something
got: 1

type something more
got: 2

您可以在第二个 input() 之前刷新输入缓冲区,就像这样

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)