python input()在调用input()之前要使用旧的stdin

时间:2019-04-04 22:17:29

标签: python python-3.x input io stdin

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

1 个答案:

答案 0 :(得分:1)

您可以在第二个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)