python input()在调用input()之前要使用旧的stdin [英] python input() takes old stdin before input() is called
本文介绍了python input()在调用input()之前要使用旧的stdin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Python3的 input()
似乎在两次调用 input()
的调用之间采用了旧的std输入.有没有办法忽略旧输入,而仅接受新输入(在 input()
被调用之后)?
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)
输出:
$ python3 input_test.py
type something
got: 1
type something more
got: 2
推荐答案
您可以在第二个 input()
之前刷新输入缓冲区,就像这样
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)
这篇关于python input()在调用input()之前要使用旧的stdin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文