首页 > 解决方案 > python input() 在调用 input() 之前采用旧的标准输入

问题描述

Python3input()似乎在两次调用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

标签: pythonpython-3.xinputiostdin

解决方案


您可以在第二个之前刷新输入缓冲区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)

推荐阅读